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

3 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by