在MATLAB中创建一个数字的数组的优雅方式?

Sib*_*ing 3 arrays matlab matrix

我知道要10 0点钟,人们可以做到

A = zeros(10, 1);
Run Code Online (Sandbox Code Playgroud)

要获得10分1,人们可以做到

A = ones(10, 1);
Run Code Online (Sandbox Code Playgroud)

任意数字怎么样?说,我想要10 3分钟.我想出了一种方法.

A = linspace(3, 3, 10);
Run Code Online (Sandbox Code Playgroud)

这令人满意吗?有更优雅的方式吗?

Lui*_*ndo 12

一些替代品:

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

功能:

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);
Run Code Online (Sandbox Code Playgroud)

方阵的基准测试脚本:

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')
Run Code Online (Sandbox Code Playgroud)

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

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

对于行数组:

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

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

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

在此输入图像描述

在此输入图像描述

在此输入图像描述


Den*_*din 7

有两种基本方法可以做到这一点:

A = ones(10,1)*3
B = zeros(10,1)+3
Run Code Online (Sandbox Code Playgroud)

第一个是最常用的例子,但如果我没有弄错,第二个表现稍好一些.总而言之,这只是一个品味问题.

当然,如果你有一个现有的矩阵,还有另一种简单的方法:

C = zeros(10,1)
C(:) = 3;
Run Code Online (Sandbox Code Playgroud)

为了完整起见,@ Luis建议的repmat解决方案也没问题.