How can I vectorize this function with nested FOR loop?

조회 수: 1 (최근 30일)
David Franco
David Franco 2018년 3월 2일
댓글: David Franco 2018년 3월 2일
The function is:
x = -10:10;
y = -5:5;
for j = 1:21
for i = 1:11
f(i) = - 20 * exp( - 0.2 * sqrt( ( 1/2 ) * sum( x(j)^2 + y(i)^2 ) ) );
end
z(j,:) = f;
end
Thanks!

채택된 답변

Andrei Bobrov
Andrei Bobrov 2018년 3월 2일
편집: Andrei Bobrov 2018년 3월 2일
% MATLAB >= R2016b
z = - 20 * exp( - 0.2 * sqrt( .5 * sum( x(:).^2 + y(:)'.^2 ) ) );
% MATLAB <= R2016a
[xx,yy] = ndgrid(x,y);
z = - 20 * exp( - 0.2 * sqrt( .5 * sum( xx.^2 + yy.^2 ) ) );
  댓글 수: 2
David Franco
David Franco 2018년 3월 2일
Thanks for the answer Andrei, but the results are different:
In the original code z = 21x11
In your codes z = 1x11
Any suggestions on how to fix this?
David Franco
David Franco 2018년 3월 2일
I figured out:
Removing the sum command the results are the same.
Thanks!

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

추가 답변 (1개)

per isakson
per isakson 2018년 3월 2일
편집: per isakson 2018년 3월 2일
Yes, try this
>> max( cssm, [], 1 )
ans =
0 0 0 0 0 0 0 0 0 0 0
>>
where
function dz = cssm()
x = -10:10;
y = -5:5;
f = nan(1,11);
z = nan(21,11);
%
for j = 1:21
for i = 1:11
f(i) = - 20 * exp( - 0.2 * sqrt( ( 1/2 ) * sum( x(j)^2 + y(i)^2 ) ) );
end
z(j,:) = f;
end
vectorized version
x02 = repmat( reshape( x, [], 1 ), 1,length(y) );
y02 = repmat( y, length(x),1 );
z02 = - 20 * exp( - 0.2 * sqrt( ( 1/2 ) * ( x02.^2 + y02.^2 ) ) );
%
dz = abs( z02 - z );
end
on R2016a
btw: Isn't true that sum in this case has no effect?
  댓글 수: 3
David Franco
David Franco 2018년 3월 2일
Thanks per isakson!

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

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by