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

3 次查看(过去 30 天)
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?

请先登录,再进行评论。

更多回答(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