截断数组 [英] Truncating an array
本文介绍了截断数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码的简化版本如下:
A simplified version of my code is as follows:
A = linspace(0,10,100);
threshold = 6.0;
我想将向量A截断到低于阈值的值.
I'd like to truncate the vector A at values below the threshold value.
假设A中的值总是递增,那么如何才能整齐而有效地做到这一点?
Assuming that the values in A are always ascending, how can I do this neatly and efficiently?
当前,我唯一想到的方法是引入一个for循环并逐个检查每个元素,如果它的值大于阈值,然后将该值分配给新数组.像这样:
Currently the only method I can think of is to introduce a for-loop and examine each element, one after another and if it has a value above the threshold, and then to allocate this value to a new array. Something like this:
k=1;
for i = 1:numel(A)
if A(i) < threshold
elseif A(i) >= threshold
Atrunc(k,1) = A(i);
k=k+1;
end
end
但是,这对我来说似乎不是很好",有人可以提供更优化的代码吗??
However this doesn't seem very 'nice' to me, can anybody offer more optimized code...?
推荐答案
使用逻辑索引
A = A(A < threshold);
或
A = A(A >= threshold);
这篇关于截断数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文