restart a for loop when a condition is met
Ältere Kommentare anzeigen
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 Kommentare
Jan
am 12 Mai 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
am 12 Mai 2018
Antworten (2)
KALYAN ACHARJYA
am 12 Mai 2018
Bearbeitet: KALYAN ACHARJYA
am 12 Mai 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 Kommentare
Jan
am 12 Mai 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
am 12 Mai 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
am 12 Mai 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 Kommentar
Frank Juang
am 12 Mai 2018
Kategorien
Mehr zu Cluster Analysis and Anomaly Detection finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!