1 view (last 30 days)

Hello, I am trying to vectorize the following simple code

if true

A=[-1;3;0;-4];

B=zeros(size(A));

for i=1:4

if A(i)<0

B(i)=-(A(i));

elseif A(i)==0

B(i)=1;

else

B(i)=A(i);

end

B=B(:);

end

end

Please, how do I write the above code in such a way that there is no for loop, and still it works?

Star Strider
on 7 Jan 2018

Try this:

A=[-1;3;-2;-4];

B = A;

B(A<0) = -A(A<0)

Star Strider
on 7 Jan 2018

This works:

A=[-1;3;0;-2;-4;0];

B = A;

B(A<0) = -A(A<0) % Change Sign Of ‘A<0’

B(A==0) = randi(9, size(A(A==0),1), size(A(A==0),2)) % Replace Values Of ‘A==0’ With Random Single Integers

I changed ‘A’ to include 2 zero values to demonstrate the code.

Star Strider
on 7 Jan 2018

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

Start Hunting!
## 2 Comments

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/375985-how-can-i-remove-for-loop-in-the-following-code-that-change-the-entries-of-a-given-vector#comment_522214

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/375985-how-can-i-remove-for-loop-in-the-following-code-that-change-the-entries-of-a-given-vector#comment_522214

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/375985-how-can-i-remove-for-loop-in-the-following-code-that-change-the-entries-of-a-given-vector#comment_522224

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/375985-how-can-i-remove-for-loop-in-the-following-code-that-change-the-entries-of-a-given-vector#comment_522224

Sign in to comment.