MATLAB Answers

Conditional 'for loop', simpler ?

4 views (last 30 days)
Ole
Ole on 10 Mar 2019
Commented: Ole on 10 Mar 2019
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 Comments
Ole
Ole on 10 Mar 2019
Thanks it is actually the X(i,j), s<X(k,j).

Sign in to comment.

Accepted Answer

madhan ravi
madhan ravi on 10 Mar 2019
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)

More Answers (0)

Products


Release

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by