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?

 採用された回答

Tigersnooze
Tigersnooze 2011 年 9 月 19 日

0 投票

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 件のコメント

Leor Greenberger
Leor Greenberger 2011 年 9 月 19 日
Thank you! this is perfect!
Leor Greenberger
Leor Greenberger 2011 年 9 月 19 日
How would I go about doing this for a matrix A where I want to check whether each element == any value in some vector b.
A(A == b) doesn't work (didn't think it would)
Sean de Wolski
Sean de Wolski 2011 年 9 月 19 日
Leor, look at ismember:
doc ismember
Leor Greenberger
Leor Greenberger 2011 年 9 月 19 日
Thank you, sir!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Multidimensional Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by