如何有效地从(非稀疏)矩阵中删除零? [英] How can I efficiently remove zeroes from a (non-sparse) matrix?

查看:112
本文介绍了如何有效地从(非稀疏)矩阵中删除零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矩阵:

x = [0 0 0 1 1 0 5 0 7 0];

我需要删除所有零,就像这样:

I need to remove all of the zeroes, like so:

x = [1 1 5 7];

我使用的矩阵很大(1x15000),我需要多次执行(5000+),所以效率是关键!

The matrices I am using are large (1x15000) and I need to do this multiple times (5000+), so efficiency is key!

推荐答案

一种方法:

x(x == 0) = [];

有关时间安排的提示

木片所述,这种方法与 KitsuneYMG 所使用的软件相比,它的速度似乎较慢.洛伦(Loren)在她的 MathWorks博客文章.由于您提到必须这样做数千次,因此您可能会发现有所不同,在这种情况下,我会先尝试x = x(x~=0);.

As mentioned by woodchips, this method seems slow compared to the one used by KitsuneYMG. This has also been noted by Loren in one of her MathWorks blog posts. Since you mentioned having to do this thousands of times, you may notice a difference, in which case I would try x = x(x~=0); first.

警告:请注意,如果您使用的是非整数.例如,如果您有一个非常小的数字,您想考虑足够接近零以便将其删除,那么上面的代码将不会删除它.仅删除 exact 零.以下内容将帮助您删除足够接近"到零的数字:

WARNING: Beware if you are using non-integer numbers. If, for example, you have a very small number that you would like to consider close enough to zero so that it will be removed, the above code won't remove it. Only exact zeroes are removed. The following will help you also remove numbers "close enough" to zero:

tolerance = 0.0001;  % Choose a threshold for "close enough to zero"
x(abs(x) <= tolerance) = [];

这篇关于如何有效地从(非稀疏)矩阵中删除零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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