필터 지우기
필터 지우기

Help with return to nested loop

조회 수: 3 (최근 30일)
Maya Harel
Maya Harel 2020년 5월 6일
댓글: Image Analyst 2020년 5월 8일
Hi, I need help with loops,
I have a while loop and in it I need to check input so I used nestef if
if the input is not valid it will print a msg and what I cannot seem to do is to send it beck to the beginning of the while loop to insert a different input
But whenever I try to print break or return at the end of the if, it just ends the whole function and not returns to the beggining of the loop
  댓글 수: 2
KSSV
KSSV 2020년 5월 6일
Show us the whole code ..
Maya Harel
Maya Harel 2020년 5월 6일
function spellMat = SpellStoring()
%the function will recive spells, check their validity and if they are
%valid, and if so it will add them to a metrix
i = 0;
x = 1;
while x==1 %will continue forever until an inside break
i = i+1; %row number
spell = input("Please enter a spell. to stop enter the word 'stop'",'s');
grade = str2double(spell(5:7)); %transfer the 5-7 varieble to one grade
if strcmp(spell,'stop') %check if writen stop
return
else %if not, continue to check validity
if isempty(intersect('HP RW HG',spell(1:2)))... %compare name to valid ones
|| isempty(intersect('ABCDEFG',spell(3)))... %compare grade to valid ones
|| isempty(intersect('IAC',spell(4)))... %compare spell to valid ones
|| grade <=100 && grade<= 000 || isempty(intersect('WSCN',spell(8)))
%check grade and tresure validity
disp('Invalid spell representation');
return
end
end
spellMat = zeros(i,8);
spellMat = [spell; spellMat];
end
end

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

채택된 답변

Julian Schmid
Julian Schmid 2020년 5월 6일
편집: Julian Schmid 2020년 5월 6일
From what I got you want to do something like that? It is easier to get an idea, if you provide the code you have written so far. The break or return statement does not end the if statement but the loop you are currently in.
inputArray = logical([1 0 1 0 0]); % can be strings and other numbers
nInput = length(inputArray);
ii = 1; % initialize index counter
while ii ~= nInput % nInput = number of arguments you want to check
if inputArray(ii) == false % or strcmp(inputArray(ii),'some condition') or ...
% input is wrong, display a message
disp('Something went wrong')
end
% increase counter
ii = ii + 1;
end
  댓글 수: 9
Maya Harel
Maya Harel 2020년 5월 6일
편집: Image Analyst 2020년 5월 8일
Thank you so much. It works!
Image Analyst
Image Analyst 2020년 5월 8일
Maya can you then "Accept this answer" to give Julian credit (reputation points) for helping you? And also to let others know it's solved and ou've moved on. Thanks in advance.

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

추가 답변 (0개)

카테고리

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