我在避免 Matlab 中的循环时遇到了麻烦。我被告知循环会导致性能不佳,所以我正在重新编写已经使用循环的代码。
我有一个包含值的向量大向量 x 和一个较小的 X,也包含值。对于每个值 x,我必须知道它在哪个区间 i。我将第 i 个区间定义为 X_i-1 和 X_i 之间的值。现在,我正在这样做:
len = length(x);
is = zeros(len, 1); % Interval for each x
for j=1:len
i=1; % Start interval
while(x(j)<X(i-1) || x(j)>X(i)) % Please consider accessing X(0) won't crash it's a simplification to make the code clearer for you.
i = i + 1;
end
is(j) = i;
end
没有这些循环的方法是什么?
编辑:为了帮助您了解情况,这是我在这里尝试做的一个真实示例。有了这些输入
X = [1 3 4 5]
x = [1 1.5 3.6 4.7 2.25]
我想is
成为
% The 2 first and the 5th are in the first interval [1, 3]
% The 3rd is in [3, 4] and the 4th is in [4, 5]
is = [1 1 2 3 1]