对于以下八度代码段:
stepTerm = zeros(3,1);
for i = 1:3
stepTerm(i,1) = some97ElementRowVector * some97by3Matrix(:,i);
end
是否可以在没有for循环的情况下编写上述代码?
答案 0 :(得分:7)
有什么问题
stepTerm = (97ElementRowVector * 97by3Matrix).';
在MATLAB上,
clc
N = 1e6;
a = rand(1,97);
B = rand(97,3);
tic
for ii = 1:N
stepTerm0 = sum(bsxfun(@times, a.', B)).';
end
toc
tic
for ii = 1:N
stepTerm1 = (a*B).';
end
toc
max(abs(stepTerm0 - stepTerm1))
给出
Elapsed time is 12.114381 seconds.
Elapsed time is 1.827436 seconds.
ans =
2.4869e-014
答案 1 :(得分:4)