# extract the indices of matrix elements after applying a condition

3 visualizzazioni (ultimi 30 giorni)
Lama Hamadeh il 15 Ott 2022
Modificato: dpb il 15 Ott 2022
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 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Dyuman Joshi il 15 Ott 2022
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

Accedi per commentare.

### Risposte (1)

dpb il 15 Ott 2022
Modificato: dpb il 15 Ott 2022
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.
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Matrix Indexing in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by