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
一些替代品:
使用repmat:
A = repmat(3, [5 7]); %// 5x7 matrix filled with the value 3
Run Code Online (Sandbox Code Playgroud)使用索引:
A(1:m, 1:n) = x;
Run Code Online (Sandbox Code Playgroud)以下是所有提议方法之间的时序比较.如您所见,@ 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的结果:



有两种基本方法可以做到这一点:
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解决方案也没问题.