Filter löschen
Filter löschen

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

5 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

dpb
dpb am 24 Feb. 2015
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...

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by