How to jump to different sections of program?
14 ビュー (過去 30 日間)
古いコメントを表示
I want to create a decision tree in MATLAB. Right now I'm using prompt and input to ask the user questions and if/else statements to move onto successive questions based on yes/no responses. However, I also want to accommodate inputs like repeat and start over that will either repeat the current question or go back to first question.
There's no goto and I'm not really sure how I can use a loop. What's the best way to implement this?
1 件のコメント
jgg
2015 年 12 月 12 日
Do you have an example? It's a little unclear what you are trying to do exactly. The easiest way that occurs to me might be to not code it as a series of statements all in a single script, but instead code each question as a function, then call it it. For example, say you have questions 1-3. For example in pseudo code:
function question1(vars) {
disp('Question 1')
input = promptForInput();
if input == 2
question2(vars,input)
else
question3(vars,input)
end
}
回答 (1 件)
Guillaume
2015 年 12 月 13 日
You could possibly code your decision tree as a state machine:
%states: each row of the states cell array corresponds to a state, the 1st column is
%descriptive test, the 2nd is the question, the 3rd row is a cell array where each row
%defines transition to another state. The 1st column of the transition is an answer to
%a question, the 2nd column is the row of the state to transition to. Note that an
%empty string is a wildcard that matches any answer not defined. A transition of -1
%exits the machine
states = {'You are in maze of twisty passageways all alike', 'Are you going "North" or "South"?', ... %state 1
{'North', 2;
'South', 3
'xyzzy', 7};
'It is very dark', 'Do you light a "Candle" or "Proceed"', ... %state 2
{'Candle', 4;
'Proceed', 5};
'It is a dead end', 'Do you "Retreat" or "Dig" the ground', ... %state 3
{'Retreat', 1;
'Dig', 6};
'A breeze extinguishes your candle', '"Light" it again or "Proceed"?', ... %state 4
{'Light', 4;
'Proceed', 5};
'You have been eaten by a grue', '"Restart" or "Quit"?', ... %state 5
{'Restart', 1;
'Quit', -1};
'You make a little hole', '"Retreat" or "Dig"?', ... % state 6
{'Retreat', 1;
'Dig', 6};
'You have been teleported to the exit and escaped', '"Restart" or "Quit"?', ... %state 7
{'Restart', 1;
'Quit', -1};
};
state = 1;
while state ~= -1
fprintf('%s\n', states{state, 1}); %print statement
while true %reprompt if invalid answer
answer = input(states{state, 2}, 's'); %ask question
answeridx = find(strcmpi(answer, states{state, 3}(:, 1))); %compare to possible answers
if ~isempty(answeridx) %if empty reprompt
state = states{state, 3}{answeridx, 2}; %move to next state
break; %break out of reprompt
end
end
end
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!