删除Matlab中特定列的带有0的行 [英] Delete rows with 0 for specific columns in Matlab

查看:2114
本文介绍了删除Matlab中特定列的带有0的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我想删除包含零的矩阵行,但仅适用于特定列.例如:

So I want to delete rows of a matrix that contain zero, but only for specific columns. For example:

A = [[0 0 0 0; 1 2 0 4; 2 0 1 1; 0 0 0 0; 1 2 3 4; 0 1 2 3];

我希望矩阵A检查第二列和/或第四列是否包含零.如果是这样:则删除整行.所以结果应该是:

I want for matrix A to check if the second and/or 4th columns contain zero's. If this is true: then delete the whole row. So the result should be:

A = [1 2 0 4; 1 2 3 4; 0 1 2 3];

我使用了此功能:

new_a = A(all(A,2),:) 

但是我删除了所有包含零的行.

But I deleted all the rows containing zeros.

推荐答案

您可以编写

>>> secondColIsNonzero = A(:, 2) ~= 0;
>>> fourthColIsNonzero = A(:, 4) ~= 0;
>>> keep = secondColIsNonzero & fourthColIsNonzero;
>>> newA = A(keep, :)
newA =
     1     2     0     4
     1     2     3     4
     0     1     2     3

保留(即不删除)第二列或第四列都不为零的列.

to keep (i.e., not delete) columns where neither the 2nd or 4th column is zero.

对于较不冗长的解决方案,请考虑同时为两个列建立索引,并将all与维参数一起使用:

For a less verbose solution, consider indexing both columns at the same time and using all with a dimension argument:

keep = all(A(:, [2 4]) ~= 0, 2)

这篇关于删除Matlab中特定列的带有0的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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