s.e
s.e

Reputation: 271

Matlab: How to update the limit of a for loop dynamically?

I'm working on the following code in 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

Although I have updated m by writing this line m=unique(x); before the for end, The limit of the for loop still has the same old value. I need to update the limit of a for loop dynamically. Is that possible? if it is possible, how to do so?

Upvotes: 3

Views: 273

Answers (1)

Jeon
Jeon

Reputation: 4076

When MATLAB meets for i = 1:length(m), it converts the statement into for i = [1 2 3 ... length(m)]. You can regard it as hard-coded. Thus, update for-limit inside a for loop does not have an effect.

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

Upvotes: 5

Related Questions