Extract rows of a matrix containing the same value in the first column by a loop

2 ビュー (過去 30 日間)
Al Falamanki
Al Falamanki 2015 年 2 月 24 日
コメント済み: Al Falamanki 2015 年 2 月 25 日
Hello I have a matrix
A = [5 10; 5 13 ; 4 31; 6 10; 6 11; 6 15 ;6 0; ... ; m p; m q;].
I want to extract each row containing the same value in the first column and build new matrices, to get:
  • A(1) = [5 10; 5 13]
  • A(2) = [4 31]
  • A(3) = [6 10; 6 11; 6 15 ;6 0]
  • ...
  • A(n) = [m p; m q]
Since the matrix A changes in number of rows and values in the first column, i want to keep it as general as possible. I tried the following code using a loop:
A = [4 10; 4 13 ; 5 31; 6 10; 6 11; 6 15 ;6 0]; % matrix
value_ind = unique(A(:,1)); % get all values from 1st column
A = sortrows(A); % sort the matrix ascending for 1st column
for i = 1:numel(value_ind)
for j = 1:numel(value_ind)
A(j) = A(A(:,1) == i,:);
end
end
Unfortunately, MATLAB says Error.
Does anyone have a suitable solution for this problem?
Thanks a lot, Al Falamanki

採用された回答

dpb
dpb 2015 年 2 月 24 日
unique is your friend...
> [u,ia,ib]=unique(A(:,1));
>> for i=1:length(u)
C(i)={A(ib==i,:)};
end
>> C{:}
ans =
4 31
ans =
5 10
5 13
ans =
6 10
6 11
6 15
6 0
>>
See
doc *accumarray*
too...
  1 件のコメント
Al Falamanki
Al Falamanki 2015 年 2 月 25 日
That's exactly what I was looking for!! Thank you very much!!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by