vectorise for loop with element wise multiplication

I have this code that I am trying to vectorize with for loop
the function is very complicated so a simplified version is
f=@(a,b) a.exp(-b);
a and b of the same size
(a=[1;2;3;4;5]; b=[6;7;8;0;0]
)
so the for loop that I am trying to vectorize is this:
z=zeros(5,5)
for i=1:5
z(: , i)=a(i)*exp(-b);
end
I am interested in having this matrix:
z=[a(1)*exp(-b) , a(2)*exp(-b) ,a(3)*exp(-b), a(4)*exp(-b) , a(5)*exp(-b) ];
The aim is to vectorise this code so faster computation is achieved
I tried using bsxfun;

 채택된 답변

Ameer Hamza
Ameer Hamza 2020년 9월 21일
편집: Ameer Hamza 2020년 9월 21일
Loops are not always necessarily slow. However, the vectorized code is much more cleaner and readable. For the simple example, you can use automatic array expansion introduced in some recent release of MATLAB. The following two code are equivalent.
a=[1;2;3;4;5]; b=[6;7;8;0;0];
z=zeros(5,5);
for i=1:5
z(: , i)=a(i)*exp(-b);
end
and
a=[1;2;3;4;5]; b=[6;7;8;0;0];
z = a.'.*exp(-b); % note a is used as a row vector and b is used as a column vector

댓글 수: 4

If the OP is using an older version , PO might have to use bsxfun() for implicit expansion
so what if I am trying to vectorize the following code :
a=[1;2;3;4;5]; b=[6;7;8;0;0]; c=[1;2;3;4;5];
z=zeros(5,5);
for i=1:5
z(: , i)=a(i)*c(i)*exp(-b);
end
Yes, on older versions, bxsfun will be used.
Muna, following is equivalent to your code
z = (a.'.*c.').*exp(-b)
Great! Thanks

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2020년 9월 21일

댓글:

2020년 9월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by