Selecting required elements from a matrix

4 ビュー (過去 30 日間)
arjun
arjun 2014 年 9 月 15 日
編集済み: Guillaume 2014 年 9 月 15 日
I have a matrix A which contains 1's and 0's I wish to construct a new matrix B such that it has all the i,j values where A(i,j)=1, i.e B will be 2 X N matrix with its elements as the indices of the elements in matrix A who have a value of 1. for eg: A=[1,0,1,1,0] then B={[1,1];[1,3];[1,4]} Thanks
  1 件のコメント
Matt J
Matt J 2014 年 9 月 15 日
B={[1,1];[1,3];[1,4]} does not produce a 2xN matrix,
>> B={[1,1];[1,3];[1,4]}
B =
[1x2 double]
[1x2 double]
[1x2 double]

サインインしてコメントする。

採用された回答

Guillaume
Guillaume 2014 年 9 月 15 日
編集済み: Guillaume 2014 年 9 月 15 日
Is this what you're after ?
[row, col] = find(A);
B = [row col]';
I.e. use the two output version of find.
edit: The above answer assumes A is not a row vector. You can use Matt J fix to handle all cases or, if you know that A is a row vector:
[row, col] = find(A);
B = [row; col];
  2 件のコメント
Matt J
Matt J 2014 年 9 月 15 日
Small fix, to handle the case when A is a row vector
B = [row(:) col(:)].';
Guillaume
Guillaume 2014 年 9 月 15 日
Oh yes, thanks!
I really hate that you can't write simple generic code in matlab because the shape of the output is not always the same.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by