필터 지우기
필터 지우기

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 CenterFile Exchange에서 Creating 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