extract the indices of matrix elements after applying a condition
    9 ビュー (過去 30 日間)
  
       古いコメントを表示
    
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
      
      
 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
BTrue
回答 (1 件)
  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.
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


