THis my code that I wrote and this code give me all possible solution but I need just the first 10 possible solution, what I can do to make it??

1 view (last 30 days)

Accepted Answer

Walter Roberson
Walter Roberson on 12 Sep 2021
It is not clear to us what a "solution" is for this purpose. We would have to guess that each place you have v=v+1 that you have just stored another "solution"
There are two approaches to consider for the case where you have multiple nested loops and you want to exit "early":
One way: Put the code that does the nested loops into a function, and call the function and then process (display) the results. Inside the function, put in tests to see if you have done enough for your purposes, and if so then use return to terminate the function. return will leave all nested loops in that function.
Second way: before the first nesting loop, assign done = false . Now, each time you increment v, immediately afterwards do
if v > required_number_of_solutions
done = true;
break;
end
Now, immediately after the end corresponding to each for do
if done; break; end
For example the code might look like
done = false;
required_number_of_solutions = 10;
for i = 1 : 10
do something
for j = 1 : 7
do something
for k = 1 : 5
do something
v = v + 1;
if v > required_number_of_solutions
done = true;
break;
end
end
if done; break; end
remaining code for j
end
if done; break; end
remaining code for i
end
The reason for this strategy is that break only leaves the inner-most level of for or while. That is unlike return in that return leaves all levels that are inside the same function.
  3 Comments
hothifa hasanat
hothifa hasanat on 13 Sep 2021
I did it but give me an error" Unrecognized function or variable 'seq' ", please help me if you can ( the file that I attached its the code after I added the things that you told me to do and its appear like this).The solutions are like the photo above

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by