Conditional 'for loop', simpler ?

1 次查看(过去 30 天)
Ole
Ole 2019-3-10
评论: Ole 2019-3-10
Is it possible make a for double loop simpler.
x=linspace(-2,2,100); s=1/2;
[X,Y]=meshgrid(x,x);
A = X.^2; B = Y;
for k=1:size(x,1)
for j=1:size(y,2)
if s<X(k,j)
L(k,j)=A(k,j).*sin(s);
M(k,j)=B(k,j).*sin(s);
else %(s>X(k,j))
L(k,j)=A(k,j).*cos(s/2);
M(k,j)=B(k,j).*cos(s/2);
end
end
end
  2 个评论
Geoff Hayes
Geoff Hayes 2019-3-10
Ole - should the condition for the if statement correspond to A(k,j) or a(k,j)?
Ole
Ole 2019-3-10
Thanks it is actually the X(i,j), s<X(k,j).

请先登录,再进行评论。

采纳的回答

madhan ravi
madhan ravi 2019-3-10
No loops needed:
L=zeros(size(A));
M=zeros(size(B));
L(s<A)=A(s<A).*sin(s);
M(s<A)=B(s<A).*sin(s)
L(s>A)=A(s>A).*cos(s/2);
M(s>A)=B(s>A).*cos(s/2)

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by