poster
2019-12-10, 16:49
我有一个矩阵:
x = [0 0 0 1 1 0 5 0 7 0]; 我需要删除所有零,像这样:
x = [1 1 5 7]; 我使用的矩阵很大(1x15000),我需要多次执行(5000+),因此效率是关键!
回答:
单程:
x(x == 0) = []; 关于时间的注意事项:
如木片 (https://stackoverflow.com/questions/738438/removing-zeros-from-a-matrix-not-sparse/738861#738861)所提到的,与KitsuneYMG (https://stackoverflow.com/questions/738438/removing-zeros-from-a-matrix-not-sparse/738484#738484)使用的方法相比,这种方法似乎慢。 Loren在其MathWorks博客文章 (http://blogs.mathworks.com/loren/2008/09/25/timing-extraction-of-parts-of-an-array/)之一中也注意到了这一点。由于您提到必须这样做数千次,因此您可能会注意到一种不同,在这种情况下,我将尝试x = x(x~=0);第一。
警告:请注意,如果您使用的是非整数。例如,如果您有一个非常小的数字,您想考虑足够接近零以便将其删除,那么上面的代码将不会删除它。仅删除精确的零。以下内容将帮助您删除“足够接近”到零的数字:
tolerance = 0.0001; % Choose a threshold for "close enough to zero" x(abs(x)
x = [0 0 0 1 1 0 5 0 7 0]; 我需要删除所有零,像这样:
x = [1 1 5 7]; 我使用的矩阵很大(1x15000),我需要多次执行(5000+),因此效率是关键!
回答:
单程:
x(x == 0) = []; 关于时间的注意事项:
如木片 (https://stackoverflow.com/questions/738438/removing-zeros-from-a-matrix-not-sparse/738861#738861)所提到的,与KitsuneYMG (https://stackoverflow.com/questions/738438/removing-zeros-from-a-matrix-not-sparse/738484#738484)使用的方法相比,这种方法似乎慢。 Loren在其MathWorks博客文章 (http://blogs.mathworks.com/loren/2008/09/25/timing-extraction-of-parts-of-an-array/)之一中也注意到了这一点。由于您提到必须这样做数千次,因此您可能会注意到一种不同,在这种情况下,我将尝试x = x(x~=0);第一。
警告:请注意,如果您使用的是非整数。例如,如果您有一个非常小的数字,您想考虑足够接近零以便将其删除,那么上面的代码将不会删除它。仅删除精确的零。以下内容将帮助您删除“足够接近”到零的数字:
tolerance = 0.0001; % Choose a threshold for "close enough to zero" x(abs(x)