按某些列值过滤矩阵 [英] Filter Matrix by some column value

查看:147
本文介绍了按某些列值过滤矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑我有这个矩阵:

   02, 04, 06, 08, 10, 2
   07, 14, 21, 28, 35, 2
   11, 22, 33, 44, 55, 0
   15, 14, 21, 28, 35, 2

我想拥有相同的矩阵,但只有最后一个column = 2的行.所以我想要这个矩阵:

I would like to have the same matrix but with only rows with last column = 2. So I want this Matrix:

   02, 04, 06, 08, 10, 2
   07, 14, 21, 28, 35, 2
   15, 14, 21, 28, 35, 2

我可以解析所有矩阵,但是还有其他方法吗?

I could parse all matrix, but is there any other way?

更准确地说,我有一个带有字符串的单元格数组:

To be more precise I have a cell array with strings:

   02, 04, Some String, 08, 10, 2
   07, 14, Some String1, 28, 35, 2
   11, 22, Some String1, 44, 55, 0
   15, 14, Some String, 28, 35, 2

推荐答案

只需在矩阵的行上使用逻辑索引:

Just use logical indexing on the rows of your matrix:

row_idx = (A(:, end) == 2);

现在row_idx包含一个1 s和0 s的逻辑数组,其中1 s的行的最后一个元素等于2.

Now row_idx contains a logical array of 1s and 0s, with 1s where the last element of the row equals 2.

现在使用以下方法过滤这些行:

Now filter these rows with:

A_filtered = A(row_idx, :);

所有这些步骤通常都是单线执行的:

All these steps are usually performed in a one-liner:

A_filtered = A(A(:, end) == 2, :);

这篇关于按某些列值过滤矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆