1

对于学校练习,我需要使用逐元素函数构建一个 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
4

5 回答 5

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 的解决方案是最快的。

于 2013-11-03T20:33:55.830 回答
2

只是为了好玩:其他可能性是

  • cumsum(repmat(1:10,[10 1]))
    
  • cell2mat(arrayfun(@(n) (n:n:10*n).',1:10,'uni',false))
    
于 2013-11-03T21:21:17.610 回答
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
于 2013-11-03T20:38:25.990 回答
0
[A,B]=meshgrid(1:10);
A.*B

使用逐元素乘法

于 2013-11-03T21:41:31.470 回答
0

我的答案是使用嵌套的 for 循环:

for i = (1:10)
    for j = (1:10) 
        fprintf('%d\t',i*j); 
    end 
    fprintf('\n'); 
end
于 2016-01-08T16:20:47.173 回答