Make loop more efficient

1 回表示 (過去 30 日間)
Panos Kerezoudis
Panos Kerezoudis 2023 年 1 月 23 日
コメント済み: Panos Kerezoudis 2023 年 1 月 23 日
Hi! I am new to Matlab and I am currently going through coding exerices to become more skilled at it.
I would appreciate any help with making my code below more efficient:
---I have an nxn matrix A and I want to increase all elements below a specific cutoff (let's say 0.5) by a certain value (let's say 1).
This is what I have so far (which thankfully works, but feels bulky).
Thanks!
for i=1:numel(A)
if A(i) < 0.5
A(i) = A(i) +1;
end
end
disp(A)

採用された回答

Matt J
Matt J 2023 年 1 月 23 日
編集済み: Matt J 2023 年 1 月 23 日
Simpler:
A=rand(5),
A = 5×5
0.7601 0.9824 0.6751 0.1206 0.7516 0.8308 0.6818 0.7500 0.7429 0.8306 0.7416 0.4895 0.6510 0.5861 0.3351 0.4752 0.9935 0.6044 0.1761 0.5067 0.9184 0.4375 0.2523 0.3061 0.4270
I=(A<0.5);
A(I)=A(I)+1,
A = 5×5
0.7601 0.9824 0.6751 1.1206 0.7516 0.8308 0.6818 0.7500 0.7429 0.8306 0.7416 1.4895 0.6510 0.5861 1.3351 1.4752 0.9935 0.6044 1.1761 0.5067 0.9184 1.4375 1.2523 1.3061 1.4270
  1 件のコメント
Panos Kerezoudis
Panos Kerezoudis 2023 年 1 月 23 日
awesome, thank you!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by