Azzera filtri
Azzera filtri

Make loop more efficient

2 visualizzazioni (ultimi 30 giorni)
Panos Kerezoudis
Panos Kerezoudis il 23 Gen 2023
Commentato: Panos Kerezoudis il 23 Gen 2023
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)

Risposta accettata

Matt J
Matt J il 23 Gen 2023
Modificato: Matt J il 23 Gen 2023
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

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by