[英]How to get selective rows from a matrix and form a new matrix in octave?
Suppose I have a matrix in octave 假设我有一个八度的矩阵
A = [2 3 5;
5 6 7;
8 9 10;
1 2 5]
Now I want to get only those rows where the last column is say equal to 5. I was wondering if there is a built in function for this, cause right now am doing it like this. 现在,我只想获取最后一列等于5的那些行。我想知道是否有内置函数可以这样做,因为现在正在这样做。
collection = [];
for i = 1 : size(matrix,1),
if(matrix(i,3) == 5),
collection = [collection; matrix(i,:)];
end
end
I would be fine if there is such a method for single column matrices. 如果有用于单列矩阵的方法,我会很好。
You can do it using logical indexing on the last column so for example 您可以使用最后一列上的逻辑索引进行操作,例如
A(:,end) == 5
returns a logical matrix which is true for the rows you want and false otherwise. 返回一个逻辑矩阵,该逻辑矩阵对所需的行为true,否则为false。 We can use this to select rows like so 我们可以像这样选择行
ind = A(:,end) == 5;
A(ind,:);
you can even just do it inline: 您甚至可以内联:
A(A(:,end)==5,:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.