Can someone do this calculation without for loops?

1 次查看(过去 30 天)
a = [1 2 3; 4 5 6];
b = [ 1 2 3 4];
c = [1 2 3 4 5];
for n = 1: size(a,1)
for m = 1:size(a,2)
for s = 1: length(b)
for k = 1: length(c)
L(n,m,s,k)= a(n,m) +b(s)*a(n,m)*exp(c(k)*a(n,m));
end
end
end
end

采纳的回答

Stephen23
Stephen23 2016-6-20
编辑:Stephen23 2016-6-20
tmp = bsxfun(@times,a,reshape(c,1,1,1,[]));
tmp = bsxfun(@times,a,exp(tmp));
tmp = bsxfun(@times,reshape(b,1,1,[]),tmp);
tmp = bsxfun(@plus,a,tmp);
Note that the floating point error propagates slightly differently, so isequal will be false.
  2 个评论
Amelos
Amelos 2016-6-21
编辑:Stephen23 2016-6-21
a =rand(2,2,3);
b = [ 1 2 3];
c = [1 2 3 4 5];
for n = 1: size(a,1)
for m = 1:size(a,2)
for s = 1: length(b)
for k = 1: length(c)
L(n,m,s,k)= a(n,m,s) +b(s)*a(n,m,s)*exp(c(k)*b(s));
end
end
end
end
Thanks for the answer! I m trying to understand the approach? What happens, if the dimension of the first matrix chances? See the example above.
Stephen23
Stephen23 2016-6-21
Well, you didn't just change the matrix dimensions, you also changed the operation by replacing the a(n,m) term inside the exp with a b(s) term. So lets do the same:
B = reshape(b,1,1,[]);
tmp = bsxfun(@times,B,reshape(c,1,1,1,[]));
tmp = bsxfun(@times,a,exp(tmp));
tmp = bsxfun(@times,B,tmp);
tmp = bsxfun(@plus,a,tmp);
and now compare some of the output values with your loop's output:
>> L(:,:,2,4)
ans =
4542.774 191.509
31.398 3096.897
>> tmp(:,:,2,4)
ans =
4542.774 191.509
31.398 3096.897

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by