having if/else statement go to previous input

77 Ansichten (letzte 30 Tage)
Kitt
Kitt am 1 Nov. 2024 um 18:52
Bearbeitet: Bruno Luong am 2 Nov. 2024 um 15:36
I have a matrix, opt, that consists of 3 outputs, 1/2/3. Output 1 goes through a bunch of steps, output 2 goes through a bunch of different steps, and if opt is 3 there's a 50/50 chance it goes through either set of steps. How do I set this up? I want something like this:
if opt == 1
abc
elseif opt == 2
xyz
else
if rand() < 0.5
opt == 1 %go back up to where "if opt == 1" is and go through steps abc
else
opt == 2 %go back up to where "if opt == 2" is and go through steps xyz
end
end
instead of having to do this:
if opt == 1
abc
elseif opt == 2
xyz
else
if rand() < 0.5
abc
else
xyz
end
end
The code is already about 1000 lines and I don't want to double it. Is there anyway I can have it go back up to where those previous elseif statements are?
  3 Kommentare
Umar
Umar am 2 Nov. 2024 um 2:20
Recursive calls can lead to stack overflow if not managed carefully, especially with deep recursion.
Walter Roberson
Walter Roberson am 2 Nov. 2024 um 6:03
or use a label with a conditional jump
I don't think I understand what you are saying there, @Umar . MATLAB does not have any concept of GOTO or labeled statements.

Melden Sie sich an, um zu kommentieren.

Antworten (3)

Torsten
Torsten am 1 Nov. 2024 um 19:03
Bearbeitet: Torsten am 1 Nov. 2024 um 19:27
r = rand();
if opt == 1 || (opt == 3 && r < 0.5)
abc
else
xyz
end

Anjaneyulu Bairi
Anjaneyulu Bairi am 1 Nov. 2024 um 19:13
Bearbeitet: Anjaneyulu Bairi am 1 Nov. 2024 um 19:14
Hi,
These are the points to be noted here:
  • If "opt" is equal to 1 then execute abc
  • If "opt" is equal to 2 then execute xyz
  • if "opt" is 3 or something else then based on rand() value execute either abc( if rand()<0.5) or xyz
Refer the below code for above logic implementation
if opt == 1 || (opt ~= 2 && rand() < 0.5)
abc
else
xyz
end

Bruno Luong
Bruno Luong am 2 Nov. 2024 um 15:29
Bearbeitet: Bruno Luong am 2 Nov. 2024 um 15:36
This is how I would do. It seems clearer to me.
if opt == 3
opt = randi([1 2]); % randi(2) is also fine
end
if opt == 1
abc
else % if opt == 2
xyz
end

Community Treasure Hunt

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

Start Hunting!

Translated by