MATLAB: How to correct the code

loopMATLABmatrix

Hello!
I wrote this code:
X=rand(5,3);
Y=zeros(5,3);
for k=1:5
for j=1:3
if X(k,j)<0.2
Y(k,j)=-1;
else
Y(k,j)=1;
end
end
end
I have to write the same code but without using any loop. How to do this?

Best Answer

%Though I am giving the answer here, but please must follow the Google "MATLAB logical indexing" as stated by @Cedric
There are multiple ways, you can do this. One way-
X=rand(5,3);
idx=X<0.2;
Y=ones(5,3);
Y(idx)=-1