MATLAB Answers

indexing a square matrix in the best possible way

5 ビュー (過去 30 日間)
Salvatore Mazzarino
Salvatore Mazzarino 2012 年 9 月 23 日
I have a square matrix and I would check some condition of every element of it.which could be the best way to indexing a square matrix using for cycle?

  1 件のコメント

Ryan
Ryan 2012 年 9 月 23 日
What condition are you looking to test? What type of points are you looking to index? For example if you have a matrix and want to find all the values greater or equal to 100 you could do:
idx_100 = A >= 100;
More complex conditions may require alternative methods.

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

回答 (3 件)

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 9 月 23 日
編集済み: Azzi Abdelmalek 2012 年 9 月 23 日
you can use cellfun for cell class or arrayfun and find for double class

  3 件のコメント

Salvatore Mazzarino
Salvatore Mazzarino 2012 年 9 月 23 日
but let's suppose I have a matrix A 2x2. I would check the condition of every element.If I had a vector I do:
for i = 1 : 10
if vector(i) some condition
do-something
end
end
but with a matrix 2x2 how can I do?
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 9 月 23 日
A=[2 3;10 25]
% that depends on the the actions that will be taken
% for examle if you wan to find index of elements of A that are >5
[idxn,idxm]=find(A>5)
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 9 月 23 日
if you want to replace all value of A that are>=3 by 100 for example
A(arrayfun(@(x) x>=3 ,A))=100
sometimes for loop can't be replaced

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


Walter Roberson
Walter Roberson 2012 年 9 月 23 日
If you are using a nested for loop, have the inner loop be over the first index.
If you are using a single for loop, just use natural index order.

  0 件のコメント

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


Image Analyst
Image Analyst 2012 年 9 月 23 日
Savatore, it depends on what you want to do. You need to tell us because that will affect the answer. For example if you have matrix A and matrix B and you want to set matrix B to 999 every place that matrix A is between 100 and 200, you'd do something like this
B(A>100 & A<200) = 999;
No for loop needed. In general, you do something like
logicalIndexes = (A == someCondition);
someMatrix(logicalIndexes) = someValue; % someMatrix could be A or some other matrix.
But if you wanted to do something like beep a tone the number of times that equals the value of A but only for all A that are less than 10, or something else that's more complicated, then you might want to use a loop.

  0 件のコメント

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

Community Treasure Hunt

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

Start Hunting!

Translated by