在Matlab中建立乘法表 [英] Build multiplication table in matlab

查看:290
本文介绍了在Matlab中建立乘法表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于学校练习,我需要使用逐元素函数构建一个乘法表10x10,并使其尽可能短. 这是我编写的代码(可以工作,但是太长了),请对这段代码提出一些建议. 在此先感谢(:

for school exercise i need to build an multiplication table 10x10 using element-by-element function, and make it as short as possible. this is the code i wrote (working but too long), please suggest some twicks to this code. thanks in advance (:

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

推荐答案

执行以下操作:

(1:10)' * (1:10)

编辑--->

当N很大时,我已经测试了Daniel,我,Luis Mendo和David建议的解决方案的速度:

I have tested the speed of the solutions suggested by Daniel, me, Luis Mendo and David, when N is large:

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大时,丹尼尔的解决方案是最快的.

So, apparently, when N is large, Daniel's solution is the fastest.

这篇关于在Matlab中建立乘法表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆