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.

 채택된 답변

Sean de Wolski
Sean de Wolski 2012년 1월 17일

1 개 추천

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

Nicklas Utgaard
Nicklas Utgaard 2012년 1월 17일
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 2012년 1월 17일
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 2012년 1월 17일
What Walter said!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Community Treasure Hunt

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

Start Hunting!

Translated by