如何在Matlab中删除向量中的零分量? [英] How to delete zero components in a vector in Matlab?

查看:223
本文介绍了如何在Matlab中删除向量中的零分量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个向量

a = [0 1 0 3]

我想将a变成等于b = [1 3]的b.

I want to turn a into b which equals b = [1 3].

通常如何执行此操作?所以我有一个带有一些零成分的向量,我想删除零并只留下非零数字吗?

How do I perform this in general? So I have a vector with some zero components and I want to remove the zeroes and leave just the non-zero numbers?

推荐答案

如果您只想删除零,将非零留在a中,那么最好的解决方法是

If you just wish to remove the zeros, leaving the non-zeros behind in a, then the very best solution is

a(a==0) = [];

这将使用MATLAB中的逻辑索引方法删除零元素.当向量的索引是与向量长度相同的布尔向量时,MATLAB可以使用该布尔结果对其进行索引.所以这等同于

This deletes the zero elements, using a logical indexing approach in MATLAB. When the index to a vector is a boolean vector of the same length as the vector, then MATLAB can use that boolean result to index it with. So this is equivalent to

a(find(a==0)) = [];

而且,当您在MATLAB中将某些数组元素设置为[]时,约定是删除它们.

And, when you set some array elements to [] in MATLAB, the convention is to delete them.

如果要将零放入新结果b中,而又保持不变,则最好的方法可能是

If you want to put the zeros into a new result b, while leaving a unchanged, the best way is probably

b = a(a ~= 0);

同样,这里使用逻辑索引.您可能已经使用了等价的版本(就结果而言)

Again, logical indexing is used here. You could have used the equivalent version (in terms of the result) of

b = a(find(a ~= 0));

但是mlint最终会将这一行标记为纯逻辑索引更有效并因此更合适的那一行.

but mlint will end up flagging the line as one where the purely logical index was more efficient, and thus more appropriate.

和往常一样,要小心接受零或任何数字的EXACT测试,如果您接受的元素在某个零容忍误差之内的话.做这样的测试

As always, beware EXACT tests for zero or for any number, if you would have accepted elements of a that were within some epsilonic tolerance of zero. Do those tests like this

b = a(abs(a) >= tol);

这仅保留至少与您的公差一样大的那些元素.

This retains only those elements of a that are at least as large as your tolerance.

这篇关于如何在Matlab中删除向量中的零分量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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