[英]Split a matrix by value in MATLAB
我想知道是否有一個MATLAB解決方案將矩陣分割成子矩陣,如下所示:
矩陣是:
A =
16 2 3
5 11 10
9 7 6
4 14 15
5 1 3
我想把以5開頭的行換成另一個矩陣,那些從16開始到另一個矩陣,等等。
是否有這個功能,或者我應該使用if / for approach?
這是一個使用函數SORTROWS , UNIQUE , ACCUMARRAY和MAT2CELL來創建單元數組的解決方案,每個單元格在第一列中存儲一組具有相同值的行:
>> sortedA = sortrows(A,1); %# Sort the rows by the first column
>> [~,~,uniqueIndex] = unique(sortedA(:,1)); %# Find indices of unique values
%# in the first column
>> cellA = mat2cell(sortedA,... %# Break matrix up by rows
accumarray(uniqueIndex(:),1),3); %# into a cell array
>> cellA{:} %# Display the contents of the cells
ans =
4 14 15
ans =
5 11 10
5 1 3
ans =
9 7 6
ans =
16 2 3
我想我發現它=)
for n=1:max(max(A))
M{n} = A(find(A(:,1)==n),:);
end
現在M{n}
是以n
開頭的所有行的矩陣。 =)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.