Make loop more efficient

2 次查看(过去 30 天)
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by