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

5 次查看(过去 30 天)
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...

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by