How to use the loops in this situation?

1 view (last 30 days)
Muhammad Usama
Muhammad Usama on 27 Dec 2018
Commented: Muhammad Usama on 3 Jan 2019
Hello!3[1 1+randperm(9)];
I have two conditions with every number comming after first digit i.e x(1). let say
a= 10*rand(1,10);
b =10*rand(1,10) ;
c = 10*rand(1,10);
d = 10*rand(1,10)
# for all values of i
if (a(i)<b(i+1) && c(i)<d(i+1))
# create new x until the above condition satisfied
otherwise proceed with the x
x = [1 1+randperm(9)];
for i = 2: nodes
while( (a(i)<b(i+1) && c(i)<d(i+1)))
goto(x)
return
end
end

Answers (1)

Elijah Smith
Elijah Smith on 27 Dec 2018
Edited: Elijah Smith on 27 Dec 2018
So, there are a few things that I noticed right off the bat.
  1. I have not seen the syntax "while if ..." and I don't believe that is correct.
  2. you used the return keyword but your code is not a function (to my knowlage)
  3. you have nothing but "goto(x)" in your while loop thus if the condition is true it will interate forever
  4. As another person metioned b, c and d are "0" because 0 times anything is still 0 : (b =0*rand(1,10); c = 0*rand(1,10); d = 0*rand(1,10)) (not a copy and paste error) this means that you will never execute the while loop.
  5. there is not a "goto" function in matlab. if this is a custom function please add the code for it.
  6. once you get to the last interation of the for loop (if I understand what your doing) you will get "index exceeds array bounds" error because some arrays are indexed with "i+1"
But if I understand what you are doing (which this is a long shot) here is some code that may help:
x = [1 1+randperm(9)];
a= 10*rand(1,10); b = rand(1,10); c = rand(1,10); d = rand(1,10);
for i = 2:length(x)
if ((a(i)<b(i+1)) && (c(i)<d(i+1)))
goto(x(i))
end
end
I may be able to answer better if you:
  1. Upload the goto function code
  2. better explain what the goal of the code is (what are you using it for)
  3. explain the need for the while loop
  4. explain what you were trying to do with the return keyword
  16 Comments
Elijah Smith
Elijah Smith on 2 Jan 2019
Edited: Elijah Smith on 2 Jan 2019
yes, but since they are determined randomly you have a specific chance as to continuing in the path. A real life situation would require you to set a, b, c and d manually and then let them update each other as nodes are visited.
Does the code I provided help? if not please Clarify what you are Asking. Your original post does not contain a question. You used loops already so it is hard to answer the question of "how to use loops in the situation?"
Muhammad Usama
Muhammad Usama on 3 Jan 2019
thank you
yes, you are right values of a,b,c and d are fixed not random. my question is just to run the loop untill i get the feasible pattern.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements 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!