1

我在避免 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] 
4

2 回答 2

4

显而易见的功课,所以我只会指出两个可能对您有所帮助的功能:

  • 如果您的间隔列表具有恒定的间距,请查看floor并弄清楚如何直接计算索引。

  • 如果间隔不规则间隔,请查看histc,尤其是查看带有 2 个输出参数的表格。

您的示例代码还有一个问题:尝试了解x(j)超出任何间隔时会发生什么。

于 2013-10-09T16:58:09.083 回答
0

我正在使用掩码,然后我移动第二个掩码,然后我使用find返回的索引:

ranges = [1,2,3,4]; %<br>
a = 1.5; %<br>
m1 = (a >= ranges); % will be [1, 0, 0, 0] <br>
m2 = (a <= ranges); % will be [0, 1, 1, 1] <br>
m2(1:end-1) = m2(2:end); % will be [1, 1, 1, 1], I am trying to shift this mask <br>
m2(end) = 0; % will be [1, 1, 1, 0], the mask shift is completed <br>
b = find( m1 & m2); % this will return 1 so your value is between 1 and 2 <br>
于 2015-05-05T00:07:35.073 回答