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

1 view (last 30 days)
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!

Accepted Answer

Matt J
Matt J on 4 Jan 2022
Edited: Matt J on 4 Jan 2022
[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 Comments
Ashfaq Ahmed
Ashfaq Ahmed on 4 Jan 2022
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?

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!