Test every element in matrix

11 views (last 30 days)
Leor Greenberger
Leor Greenberger on 19 Sep 2011
I have an M x N matrix, where I want to test whether each element is greater than some constant a, and if it is, perform some arithmetic to it. The only way I can think of doing this is using 2 For loops nested to select each element and an If statement to perform checking. Is this the best I can do?

Accepted Answer

Tigersnooze
Tigersnooze on 19 Sep 2011
You can say something like this, instead of using a loop (assuming the matrix is called A):
A(A > a) = A(A > a) + arithmetic.
"Vectorizing" like this won't have significant speed advantages with smaller matrices, but when the matrix gets bigger you'll see huge time savings. Just a heads up for the future.
  4 Comments
Sean de Wolski
Sean de Wolski on 19 Sep 2011
Leor, look at ismember:
doc ismember
Leor Greenberger
Leor Greenberger on 19 Sep 2011
Thank you, sir!

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!