Effacer les filtres
Effacer les filtres

Make loop more efficient

2 vues (au cours des 30 derniers jours)
Panos Kerezoudis
Panos Kerezoudis le 23 Jan 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)

Réponse acceptée

Matt J
Matt J le 23 Jan 2023
Modifié(e) : Matt J le 23 Jan 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
  1 commentaire
Panos Kerezoudis
Panos Kerezoudis le 23 Jan 2023
awesome, thank you!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by