필터 지우기
필터 지우기

How can I use the "diff" function instead of a for loop?

조회 수: 4 (최근 30일)
Ashfaq Ahmed
Ashfaq Ahmed 2022년 1월 4일
댓글: Matt J 2022년 1월 4일
Dear altruists,
How can I get the similar result from this few lines of code using the MATLAB built in "diff" function instead of using the for loop?
g = 9.807;
for i=2:size(lon,1)-1
for j=2:size(lat,2)-1
dx=double(m_lldist([lon(i+1) lon(i-1)],[lat(j) lat(j)]))*1000;
dy=double(m_lldist([lon(i) lon(i)],[lat(j+1) lat(j-1)]))*1000;
f=2*(omega)*sin((lat(j)*(pi/180)));
u(i,j)=-g/f*(ssh(i,j+1)-ssh(i,j-1))/dy;
v(i,j)= g/f*(ssh(i+1,j)-ssh(i-1,j))/dx;
end
end
the size of the variables: lat, lon, and ssh is the same. (size:71*294)
Any feedback from you will be highly appreciated. Happy new year all!

채택된 답변

Matt J
Matt J 2022년 1월 4일
편집: Matt J 2022년 1월 4일
[m,n]=size(ssh);
zm=zeros(m,1);
zn=zeros(1,n);
gf=g./(2*omega*sind( lat ) );
Du=diff(ssh(:,2:end),1,2)+diff(ssh(:,1:end-1),1,2);
Du=-gf.*[zm,Du,zm];
Dv=diff(ssh(2:end,:),1,1)+diff(ssh(1:end-1,:),1,1);
Dv=gf.*[zn;Dv;zn];
[dx,dy]=deal(ones(size(Du)));
for i=2:size(lon,1)-1
for j=2:size(lat,2)-1
dx(i,j)=double(m_lldist([lon(i+1) lon(i-1)],[lat(j) lat(j)]))*1000;
dy(i,j)=double(m_lldist([lon(i) lon(i)],[lat(j+1) lat(j-1)]))*1000;
end
end
u=Du./dy;
v=Dv./dx;
  댓글 수: 2
Ashfaq Ahmed
Ashfaq Ahmed 2022년 1월 4일
Hi Matt,
Thank you so much for your effort on my question. Unfortunately, I fogrot to include that, the g in my code is a variable with a constant value.
g = 9.807;
I ran your code and it is not giving me the values that I am expecting. Do you think it was because of the g?
Matt J
Matt J 2022년 1월 4일
No, I assumed g to be a scalar constant.

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

추가 답변 (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