フィルターのクリア

How to find specific elements in a matrix

40 ビュー (過去 30 日間)
Kendal
Kendal 2022 年 11 月 8 日
回答済み: Walter Roberson 2022 年 11 月 8 日
Good Day,
I have a matrix: R55 = [2,4,6,9,11;7,8,9,10,6;1,2,6,4,5;,6,9,8,5,6;1,6,5,7,5];
I would like to find the specific locations of all the 6's (rows and colums) using a for loop and using logical matrices rather than using just the "find" function.

採用された回答

Voss
Voss 2022 年 11 月 8 日
R55 = [2,4,6,9,11;7,8,9,10,6;1,2,6,4,5;,6,9,8,5,6;1,6,5,7,5]
R55 = 5×5
2 4 6 9 11 7 8 9 10 6 1 2 6 4 5 6 9 8 5 6 1 6 5 7 5
val = 6;
Using a for loop:
rows = [];
columns = [];
m = size(R55,1);
for ii = 1:numel(R55)
if R55(ii) == val
rows(end+1) = mod(ii-1,m)+1;
columns(end+1) = ceil(ii/m);
end
end
rows, columns
rows = 1×6
4 5 1 3 2 4
columns = 1×6
1 2 3 3 5 5
Using two nested for loops:
rows = [];
columns = [];
[m,n] = size(R55);
for jj = 1:n
for ii = 1:m
if R55(ii,jj) == val
rows(end+1) = ii;
columns(end+1) = jj;
end
end
end
rows, columns
rows = 1×6
4 5 1 3 2 4
columns = 1×6
1 2 3 3 5 5
Using a logical matrix, without find:
is_val = R55 == val
is_val = 5×5 logical array
0 0 1 0 0 0 0 0 0 1 0 0 1 0 0 1 0 0 0 1 0 1 0 0 0
idx = 1:numel(R55);
[rows,columns] = ind2sub(size(R55),idx(is_val))
rows = 1×6
4 5 1 3 2 4
columns = 1×6
1 2 3 3 5 5

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2022 年 11 月 8 日
This kind of task is usually easier to write with nested for loops over size() of the array. If you are required to use a single for loop then loop over the linear indices and ind2sub to translate to row and column

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by