extract the indices of matrix elements after applying a condition

조회 수: 6 (최근 30일)
Lama Hamadeh
Lama Hamadeh 2022년 10월 15일
편집: dpb 2022년 10월 15일
Hi,
I have the following two matrices:
A = [1.0000 2.0000;
0.1000 1.0000 ;
0.6000 0.4000 ;
5.0000 0.1000 ;
0.4000 0 ;
0.4000 2.0000 ];
B = [1 ;
3 ;
5 ;
0.4;
5.4;
6.2];
A condition is applied on matrix A to extract certain elements from it as following:
ATrue = [];
for i = 1:size(A,1)
ind = find(A(i,:) >= 0) & (A(i,:) <= 1);
if ind == true
ATrue = [ATrue ; A(i,ind)]
end
end
I want to know the indicies of these elements so I can extract the same indicies from matrix B, so I can get the result of:
B =
5.0000
3.0000
5.4000
How can I do that?
  댓글 수: 1
Dyuman Joshi
Dyuman Joshi 2022년 10월 15일
You have the correct idea, you just need a little tweak in the code
A = [1.0000 2.0000;
0.1000 1.0000 ;
0.6000 0.4000 ;
5.0000 0.1000 ;
0.4000 0 ;
0.4000 2.0000 ];
B = [1; 3; 5; 0.4; 5.4; 6.2];
ATrue = [];
BTrue=[];
for i = 1:size(A,1)
%It seems like you are checking if all elements in a row to satisy the
%condition
ind = all(A(i,:) >= 0 & A(i,:) <= 1);
if ind
ATrue = [ATrue; A(i,:)];
BTrue = [BTrue; B(i,1)];
end
end
ATrue
ATrue = 3×2
0.1000 1.0000 0.6000 0.4000 0.4000 0
BTrue
BTrue = 3×1
3.0000 5.0000 5.4000

댓글을 달려면 로그인하십시오.

답변 (1개)

dpb
dpb 2022년 10월 15일
편집: dpb 2022년 10월 15일
A = [1.0000 2.0000;
0.1000 1.0000 ;
0.6000 0.4000 ;
5.0000 0.1000 ;
0.4000 0 ;
0.4000 2.0000 ];
B = [1 ;
3 ;
5 ;
0.4;
5.4;
6.2];
The comment above from @Dyuman Joshi fixes the given code using the for...end construct, but MATLAB is not named for MATrix Laboratory for nothing...
Try
ix=all(A>=0&A<=1,2);
Or move the multiple comparison down a level to be less of a distraction reading the code --
ix=all(iswithin(A,0,1),2);
where iswithin is my "syntactic sugar" utility routine --
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
NOTA BENE: The use of the optional second dim argument to all to operate on the second dimension (columns) to return the row indices as a column vector instead of the default by row.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by