我有一个矩阵,它是从文本文件中读取的二维数组。每行文本文件有3个条目。第3列的值范围为1到4.我想基于此值分隔行并将它们放入不同的矩阵中。你能建议一个办法吗?
答案 0 :(得分:2)
对于矩阵M
,正如您所描述的那样
rowsContainingOne = M( M(:,3)==1, :)
rowsContainingTwo = M( M(:,3)==2, :)
rowsContainingThree = M( M(:,3)==3, :)
rowsContainingFour = M( M(:,3)==4, :)
要了解其工作原理,请查看以下部分的结果:
M(:,3) %A vector of column three
M(:,3)==1 %A logical array, `true` where column 3 equals one
M( M(:,3)==1, :) %All columns (indicated by `:`) from rows where the logical array is `true`
答案 1 :(得分:0)
使用函数sortrows
。
伪代码:
%% Creating a matrix of the type you have mentioned.
A = zeros(10,3); A(:,1:2) = rand(10,2); A(:,3)=randi(4,10,1);
%% Use the "sortrows" function to sort all the rows as per the entries in column-3 of A
B = sortrows(A,3);