フィルターのクリア

Extract some rows of the matrix with the find command

2 ビュー (過去 30 日間)
Alberto Acri
Alberto Acri 2023 年 8 月 18 日
編集済み: dpb 2023 年 8 月 19 日
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];

採用された回答

Dyuman Joshi
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,:)
out = 4×3
7 6 0 11 6 0 12 6 2 13 6 0

その他の回答 (1 件)

dpb
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...
Very similar to @Dyuman Joshi's solution but not quite as expensive as ismember...
>> 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
>>

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by