Given a large matrix containing values in range [0,1].
Is it possible to change (as in, set to fixed value, add value, subtract value ect.) elements above a certain threshold, without the use of loops? And without changing the rest of the matrix.

 Réponse acceptée

Sean de Wolski
Sean de Wolski le 17 Jan 2012

1 vote

Of course - use logical indexing:
A = rand(5);
A(A>0.5) = 10; %set all values in a greater than 0.5 to 10

3 commentaires

Nicklas Utgaard
Nicklas Utgaard le 17 Jan 2012
Thanks. :)
I see how this would work for setting fixed value. But how about adding and subtracting? Is there an easy way? What I have so far is
B = rand(5);
B = B-(B > 0.5)/5; % subtracts 0.2 from all the values greater then 0.5.
Is there any easier way? And how would this work if I wanted to subtract 50% off of each value greater then 0.5?
Walter Roberson
Walter Roberson le 17 Jan 2012
Normally people would write
idx = B>0.5;
B(idx) = B(idx) - 0.2;
B(idx) = B(idx) / 2;
Sean de Wolski
Sean de Wolski le 17 Jan 2012
What Walter said!

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by