How can I remove for loop in the following code that change the entries of a given vector?

1 回表示 (過去 30 日間)
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?
  2 件のコメント
Matt J
Matt J 2018 年 1 月 7 日
Please indent your code, but not your text. It makes your post hard to read, otherwise.

サインインしてコメントする。

採用された回答

Star Strider
Star Strider 2018 年 1 月 7 日
Try this:
A=[-1;3;-2;-4];
B = A;
B(A<0) = -A(A<0)
  6 件のコメント
Star Strider
Star Strider 2018 年 1 月 7 日
Note that it is necessary to determine the number of zeros, so the vector of non-zero values that replaces them is the same size. I used random single-digit positive integers, although any vector with the same number of non-zero values as there are zero values in the vector will work.

サインインしてコメントする。

その他の回答 (1 件)

Matt J
Matt J 2018 年 1 月 7 日
編集済み: Matt J 2018 年 1 月 7 日
B=abs(A);
B(~A)=1; %or any other value

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by