问题描述
我有一个矩阵:
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) = [];
关于时间的说明:
正如 woodchips 所提到的,这种方法与 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.
警告:请注意,如果您使用的是非整数数字.例如,如果您有一个非常小的数字,您希望将其考虑为足够接近零以便将其删除,则上述代码不会将其删除.仅删除精确 零.以下内容也将帮助您删除足够接近"为零的数字:
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) = [];
这篇关于如何有效地从(非稀疏)矩阵中删除零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!