restart a for loop when a condition is met
Show older comments
Hi, I want to add a loop to restart kmeans function three times when the condition is met. After running this loop, the condition is still met,then loop j will add 1 (it means that the kmeans function will be grouped j+1 clusters. )
for j = 1 : member;
[id1,C1,sumd1,d1] = kmeans(gg{m}{i},j,'Distance','sqeuclidean');
for k =1:j
d ; %output
if d > 1.5
% when condition is met, restart a loop (restart kmeans function)three times.
end
end
end
2 Comments
Jan
on 12 May 2018
Neitehr d not the condition d > 1.5 depends on the inner loop "for k". So what is the purpose of this loop? What is "member"?
Frank Juang
on 12 May 2018
Answers (2)
KALYAN ACHARJYA
on 12 May 2018
Edited: KALYAN ACHARJYA
on 12 May 2018
if true
% code
for j = 1 : member;
myfunction();
for k =1:j;
if d > 1.5
j=1; % if you want return to 1st for loop
%or
k=1; % if you want return to 2nd for loop
end
end
end
2 Comments
Jan
on 12 May 2018
No, you cannot modify the loop counter of a FOR loop by changing the value inside the loop. Try it:
for k = 1:10
disp(k)
if k == 5
k = 8
end
end
Image Analyst
on 12 May 2018
Well you can but it's not good practice and only keeps the new value until the end of the loop and then goes back to what it would have been once the loop starts from the top.
If you want to change variables like loop counters inside a loop you should use a while loop instead.
Jan
on 12 May 2018
What about this:
for j = 1:4
[id1, C1, sumd1, d1] = kmeans(gg{m}{i},j,'Distance','sqeuclidean');
if all(d1 <= 1.5)
break;
end
end
Then the loop runs either 3 times more or is stopped earlier, when the condition is met.
1 Comment
Frank Juang
on 12 May 2018
Categories
Find more on k-Means and k-Medoids Clustering in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!