How to vectorize the following code snippet ?

M = randi([-10 10],10,10);
[m, n] = size(M);
out = zeros(m, n);
for x = 1:m
for y = 1:n
if M(x, y) > 0
out(x, y) = 1;
else if M(x, y) == 0
out(x, y) = 0;
else
out(x, y)=-1;
end
end
end

 採用された回答

Star Strider
Star Strider 2021 年 2 月 15 日

0 投票

That can all be reduced to:
out = zeros(size(M))-1;
out(M>0) = 1;
out(M==0) = 0;
producing the same result.

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeSimulink Functions についてさらに検索

製品

リリース

R2020b

質問済み:

2021 年 2 月 15 日

回答済み:

2021 年 2 月 15 日

Community Treasure Hunt

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

Start Hunting!

Translated by