restart a for loop when a condition is met

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
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
Frank Juang am 12 Mai 2018
I want to add a loop to restart kmeans function three times if d >1.5.The loop j is used to run kmeans function for 1: v(member is the size of my input),so the code will group from one cluster to member clusters.

Melden Sie sich an, um zu kommentieren.

Antworten (2)

KALYAN ACHARJYA
KALYAN ACHARJYA am 12 Mai 2018
Bearbeitet: KALYAN ACHARJYA am 12 Mai 2018

0 Stimmen

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

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
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.

Melden Sie sich an, um zu kommentieren.

Jan
Jan am 12 Mai 2018

0 Stimmen

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
Frank Juang am 12 Mai 2018
Sorry, maybe I describe dully. Actually,the d in loop k is calculated by the output of kmeans function in loop j.Loop j is used to group my data from one to member clusters(member is the size of my input). My purpose is used less clusters as far as possible,so I want to restart kmeans function several times before doing j+1.If running kmeans function several times d is still large than 1.5, then j will become j+1.

Melden Sie sich an, um zu kommentieren.

Kategorien

Gefragt:

am 12 Mai 2018

Kommentiert:

am 12 Mai 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by