Extract some rows of the matrix with the find command
1 回表示 (過去 30 日間)
古いコメントを表示
Hi. I would like to select rows from a 'matrix' array that have values between 0 and 2 in the third column of 'matrix'. I was able to select the desired rows but how can I combine them to create a unique matrix?
matrix = [6 6 5
7 6 0
8 6 10
9 6 3
10 6 7
11 6 0
12 6 2
13 6 0];
for k = 1:height(matrix)
for selected_number = 0:2
search = find(matrix(:,3) == selected_number);
select_row = matrix(search,:);
end
end
The output should be:
matrix_out = [7 6 0
11 6 0
12 6 2
13 6 0];
0 件のコメント
採用された回答
Dyuman Joshi
2023 年 8 月 18 日
Use ismember with logical indexing -
matrix = [6 6 5
7 6 0
8 6 10
9 6 3
10 6 7
11 6 0
12 6 2
13 6 0];
idx = ismember(matrix(:,3),0:2);
out = matrix(idx,:)
0 件のコメント
その他の回答 (1 件)
dpb
2023 年 8 月 18 日
編集済み: dpb
2023 年 8 月 19 日
Perfect application for a little utility function I keep around -- as a sidelight, I create and add to my MATLABPATH a "Utilities" folder that contains such tidbits as this; little tools that are handy but not built into base MATLAB distribution...
>> out=matrix(iswithin(matrix(:,3),0,2),:)
out =
7 6 0
11 6 0
12 6 2
13 6 0
>>
where iswithin is the utility function to return the logical indexing array. This is an extremely handy construct to be able to throw the details of the comparison into a black box and just return the result even for simple cases like this; it's even more useful in cases with multiple conditions or the like.
>> type iswithin.m
function flg=iswithin(x,lo,hi)
% returns T for values within range of input
% SYNTAX:
% [log] = iswithin(x,lo,hi)
% returns T for x between lo and hi values, inclusive
flg= (x>=lo) & (x<=hi);
end
>>
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Resizing and Reshaping Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!