Extract rows of a matrix containing the same value in the first column by a loop
조회 수: 2 (최근 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
댓글 수: 0
채택된 답변
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 Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!