Matlab:如何动态更新for循环的限制?

s.e*_*s.e 3 matlab for-loop updates limit

我在matlab中处理以下代码:

m=unique(x);
for i=1:length(m)
%some code that increase the number of unique values in x
.......
.......
%here I tried to update m 
m=unique(x);
end
Run Code Online (Sandbox Code Playgroud)

虽然我已经m通过m=unique(x);在for end之前写这行来更新,但for循环的限制仍然具有相同的旧值.我需要动态更新for循环的限制.那可能吗?如果有可能,该怎么办?

Jeo*_*eon 5

当MATLAB满足时for i = 1:length(m),它将语句转换为for i = [1 2 3 ... length(m)].您可以将其视为硬编码.因此,在for循环内更新for-limit没有效果.

m = unique(x);
i = 1;
while true
    if i > length(m)
        break
    end
    % do something
    i = i + 1;
    m = unique(x);
end
Run Code Online (Sandbox Code Playgroud)

  • 或者,更简单一点:`m = unique(x); ii = 0; 而ii <numel(m),ii = ii + 1; 做一点事; m =唯一(x); end` (7认同)