How can I use the "diff" function instead of a for loop?
1 次查看(过去 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!
0 个评论
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!