gpt4 book ai didi

arrays - 在 MATLAB 中创建一个充满一个数字的数组的优雅方法?

转载 作者:太空宇宙 更新时间:2023-11-03 20:09:30 26 4
gpt4 key购买 nike

我知道要获得 10 个 0,一个人可以做到

A = zeros(10, 1);

要获得 10 个 1,一个人可以做到

A = ones(10, 1);

任意数字呢?比如说,我想要 10 个 3。我想到了一种方法。

A = linspace(3, 3, 10);

这个满意吗?有更优雅的方法吗?

最佳答案

一些备选方案:

  • 使用 repmat :

    A = repmat(3, [5 7]); %// 5x7 matrix filled with the value 3
  • 使用索引:

    A(1:m, 1:n) = x;

以下是所有提议方法之间的时间比较。如您所见, @Dennis' solutions是最快的(至少在我的系统上)。

函数:

function y = f1(x,m,n) %// Dennis' "ones"
y = x*ones(m,n);

function y = f2(x,m,n) %// Dennis' "zeros"
y = x+zeros(m,n);

function y = f3(x,m,n) %// Luis' "repmat"
y = repmat(x,[m n]);

function y = f4(x,m,n) %// Luis' "dirty"
y(m,n) = 0;
y(:) = x;

function y = f5(x,m,n) %// Luis' "indexing"
y(1:m,1:n) = x;

function y = f6(x,m,n) %// Divakar's "matrix porod"
y = x*ones(m,1)*ones(1,n);

方形数组的基准测试脚本:

x = 3;
sizes = round(logspace(1,3.7,10)); %// max limited by computer memory
for s = 1:numel(sizes)
n = sizes(s);
m = sizes(s);
time_f1(s) = timeit(@() f1(x,m,n));
time_f2(s) = timeit(@() f2(x,m,n));
time_f3(s) = timeit(@() f3(x,m,n));
time_f4(s) = timeit(@() f4(x,m,n));
time_f5(s) = timeit(@() f5(x,m,n));
time_f6(s) = timeit(@() f6(x,m,n));
end
loglog(sizes, time_f1, 'r.-');
hold on
loglog(sizes, time_f2, 'g.:');
loglog(sizes, time_f3, 'b.-');
loglog(sizes, time_f4, 'm.-');
loglog(sizes, time_f5, 'c.:');
loglog(sizes, time_f6, 'k.:');
xlabel('Array size')
ylabel('Time')
legend('ones', 'zeros', 'repmat', 'dirty', 'indexing', 'matrix prod')

对于列数组:只需更改以下行:

sizes = round(logspace(1,3.7,10)).^2; %// max limited by computer memory
n = 1;
m = sizes(s);

对于行数组:

sizes = round(logspace(1,3.7,10)).^2; %// max limited by computer memory
n = sizes(s);
m = 1;

双核 CPU、2 GB RAM、Windows Vista、Matlab R2010b 的结果:

  1. 方阵;
  2. 列数组;
  3. 行数组。

enter image description here

enter image description here

enter image description here

关于arrays - 在 MATLAB 中创建一个充满一个数字的数组的优雅方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26714067/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com