How to use the loops in this situation?

조회 수: 2 (최근 30일)
Muhammad Usama
Muhammad Usama 2018년 12월 27일
댓글: Muhammad Usama 2019년 1월 3일
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

답변 (1개)

Elijah Smith
Elijah Smith 2018년 12월 27일
편집: Elijah Smith 2018년 12월 27일
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
Elijah Smith
Elijah Smith 2019년 1월 2일
편집: Elijah Smith 2019년 1월 2일
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 2019년 1월 3일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by