对于学校练习我需要使用逐元素函数构建乘法表10x10,并使其尽可能短。 这是我写的代码(工作但太长),请为此代码提出一些建议。 提前谢谢(:
base=zeros(10);
oneten=[1:1:10];
base(1,:)=1.*oneten;
base(2,:)=2.*oneten;
base(3,:)=3.*oneten;
base(4,:)=4.*oneten;
base(5,:)=5.*oneten;
base(6,:)=6.*oneten;
base(7,:)=7.*oneten;
base(8,:)=8.*oneten;
base(9,:)=9.*oneten;
base(10,:)=10.*oneten
答案 0 :(得分:4)
做这样的事情:
(1:10)' * (1:10)
编辑--->
当N很大时,我测试了Daniel,我,Luis Mendo和David建议的解决方案的速度:
N = 100; % number of iterations
runtime_a = zeros(N, 1); % runtime of Daniel's solution
runtime_b = zeros(N, 1); % runtime of the obvious solution
runtime_c = zeros(N, 1); % runtime of Luis Mendo's solution
runtime_d = zeros(N, 1); % runtime of Luis Mendo's solution
runtime_e = zeros(N, 1); % runtime of David's solution
n = 5000; % number of elements
one_to_n = 1:n;
for hh = 1:N
% Solution by Daniel R.
tic, a = bsxfun(@times, one_to_n, one_to_n'); runtime_a(hh) = toc;
clear a
tic, b = one_to_n' * one_to_n; runtime_b(hh) = toc;
clear b
% Solution by Luis Mendo
tic, c = cell2mat(arrayfun(@(x) (x:x:n*x).', one_to_n, 'uni', false)); runtime_c(hh) = toc;
clear c
% Solution by Luis Mendo.
tic, d = cumsum(repmat(one_to_n, [n 1])); runtime_d(hh) = toc;
clear d
% Solution by David
tic, [A, B] = meshgrid(one_to_n); e = A.*B; runtime_e(hh) = toc;
clear e
end
% Check mean and standard deviation:
mean([runtime_a, runtime_b, runtime_c, runtime_d, runtime_e])
std([runtime_a, runtime_b, runtime_c, runtime_d, runtime_e])
结果是:
% mean:
0.105048900691251 0.188570704057917 0.491929288458701 0.787045026437718 0.979624197407329
% standard deviation:
0.034274873626281 0.077388368324427 0.163983982925543 0.285395301735065 0.372693172505310
所以,显然,当N很大时,Daniel的解决方案是最快的。
答案 1 :(得分:2)
只是为了它的乐趣:其他可能性
cumsum(repmat(1:10,[10 1]))
cell2mat(arrayfun(@(n) (n:n:10*n).',1:10,'uni',false))
答案 2 :(得分:1)
oneten=[(1:10)]
base = bsxfun(@times,oneten,oneten')
在这种情况下,预分配(base=zeros(10);
)是无效的。
另一个更容易理解的解决方案:
base=zeros(10);
oneten=[(1:10)];
for k=oneten
base(k,:)=k.*oneten;
end
答案 3 :(得分:0)
[A,B]=meshgrid(1:10);
A.*B
使用逐元素乘法
答案 4 :(得分:0)
我的回答是使用嵌套for循环:
for i = (1:10)
for j = (1:10)
fprintf('%d\t',i*j);
end
fprintf('\n');
end