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

9 visualizzazioni (ultimi 30 giorni)
The code is up in the file👆👆👆

Risposta accettata

Walter Roberson
Walter Roberson il 12 Set 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 Commenti
Walter Roberson
Walter Roberson il 13 Set 2021
done = false;
required_number_of_solutions = 10;
Copy those literally and put them above your first for loop.
if v > required_number_of_solutions
done = true;
break;
end
Put a copy of that immediately after every time you have v=v+1;
if done; break; end
Put a copy of that immediately after the end statement for all inner for loops, but not after the outermost for-loop.
Think of it as practice in editting.
hothifa hasanat
hothifa hasanat il 13 Set 2021
Modificato: hothifa hasanat il 13 Set 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

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by