how to vectorized a nested for loop?

i have two for loop and i want to vectorized it . i try a lot to do it but i cannot do it. this is the simple version is let
Mat = zeros(10)
for i = 1:10
for j = 1:10
Mat(i,j) = exp((i.^5) + j.^2);
end
end
Thanks.......

답변 (1개)

Jan Orwat
Jan Orwat 2014년 2월 13일
편집: Jan Orwat 2014년 2월 14일

0 개 추천

Hello Mohammed, there are many ways to vectorize your loops. Check out those examples:
1.
[r,c]=meshgrid(1:10,1:10);
Mat=exp(c.^5+r.^2);
check function meshgrid in help to how it works (type doc meshgrid in commmand window)
2.
Mat=bsxfun(@(A,B)exp(A.^5+B.^2),(1:10)',1:10);
check bsxfun and function_handle
  • Also, please consider the fact that in your example, and in proposed vectorizations in matrix Mat columns from 4 to 10 have values equal to infinity due to maximum capacity of data precision.

댓글 수: 4

thanks for your answer
a = zeros(10);
for i=1:10
for j=1:10
a(i,j) = exp(i.^5+j.^2)
end
end
[r,c]=meshgrid(1:10,1:10);
Mat=exp(r.^5+c.^2);
Mat1=bsxfun(@(A,B)exp(A.^5+B.^2),1:10,(1:10)');
isequal(a,Mat)
result is 0 which means both answers are not same.
mohammed
mohammed 2014년 2월 14일
i think you just miss one thing that is Transpose of a matrix....... by the way Thanks. and edit the answer so that other can also get benifits...
Jan Orwat
Jan Orwat 2014년 2월 14일
Thanks Mohammed, I've updated the answer. Now it is correct.
Jung Soo Park
Jung Soo Park 2018년 2월 21일
there are two minor errors on mohammed's reply dated 14feb2014. a=zeros(10,10) and isequal(a,Mat1)

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

질문:

2014년 2월 13일

댓글:

2018년 2월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by