이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
Problem with an if statement
조회 수: 3 (최근 30일)
이전 댓글 표시
Tariq Hammoudeh
2021년 12월 30일
I have this code:
orientation= input (' enter v or h')
if orientation == v
......
end
but whenever i run the code and enter v or h, I get an error saying
Unrecognized function or variable 'v'.
So does matlab not take inputs in letters or is there a way to make it work.
채택된 답변
Voss
2021년 12월 30일
Use the optional second argument to the input() function, 's', which tells input() to return exactly what the user entered, without evaluating it. You'll also need to compare orientation to 'v' rather than v or you'll just get the same error on the next line (and use strcmp/strcmpi in case they entered more than one character or an empty string).
orientation= input (' enter v or h', 's')
if strcmp(orientation,'v')
% do v stuff
else
% do h stuff
end
댓글 수: 11
Tariq Hammoudeh
2021년 12월 30일
편집: Tariq Hammoudeh
2021년 12월 30일
Thank you, for that but i just ended up using
if orientation == 'v'
....
But i have another question related to this,
Im using
if orientation == 'v'
....
elseif orientation == 'h'
.....
else
disp('choose v or h only')
end
How can i make it so that if neither v nor h are entered it displays this message and allows the user to try again
Voss
2021년 12월 30일
orientation = '';
while ~ismember(orientation,{'v' 'h'})
orientation = input(' enter v or h', 's');
if strcmp(orientation,'v')
% do v stuff
elseif strcmp(orientation,'h')
% do h stuff
else
disp('choose v or h only');
end
end
Or:
while true
orientation = input(' enter v or h', 's');
if ismember(orientation,{'v' 'h'})
break;
end
disp('choose v or h only');
end
if strcmp(orientation,'v')
% do v stuff
else
% do h stuff
end
Tariq Hammoudeh
2021년 12월 30일
ok just one more thing, I joined this with my code and now its like this:
startingGrid= input(' Please choose the grid number you want your ship to start in : ');
if startingGrid == 1
while true
orientation = input(' Please enter v if you want your ship to be placed vertically or h if you want it horizontally', 's');
if ismember(orientation,{'v' 'h'})
break;
end
disp(' please choose v or h only and make sure to use small letters ');
end
if strcmp(orientation,'v')
.....
else
.....
end
I have many of those if statements, and i need to be able to let the user enter another startingGrid if they chose a specific number then either v or h. So basically in the
% do v stuff
or
% do h stuff
i tried
startingGrid=input('please try again')
but whenever i enter a different number the program just ends.
please note those "specific numbers" are things that i have different code to detect, so i only need the program to continue when i "try again", this is the only issue
Voss
2021년 12월 30일
I would make the startingGrid input and the orientation input independent of each other. Something along the lines of this:
while true
startingGrid = input(' Please choose the grid number you want your ship to start in : ');
% validate startingGrid with your other code here
if startingGrid >= 1 && startingGrid <= 10 % whatever your valid condition is
break
end
disp('please try again');
end
while true
orientation = input(' Please enter v if you want your ship to be placed vertically or h if you want it horizontally', 's');
if ismember(orientation,{'v' 'h'})
break
end
disp(' please choose v or h only and make sure to use small letters ');
end
then validate startingGrid and orientation together after that, i.e., check some condition(s) that depend(s) on both startingGrid and orientation, which is not possible to check until both have been input.
This way you only ever need one while loop for each input, rather than many.
You probably will want to wrap that whole thing in a while loop too, for the consistency check between startingGrid and orientation:
while true
while true
startingGrid = input(' Please choose the grid number you want your ship to start in : ');
% validate startingGrid with your other code here
if startingGrid >= 1 && startingGrid <= 10 % whatever your valid condition is
break
end
disp('please try again');
end
while true
orientation = input(' Please enter v if you want your ship to be placed vertically or h if you want it horizontally', 's');
if ismember(orientation,{'v' 'h'})
break
end
disp(' please choose v or h only and make sure to use small letters ');
end
% check consistency between startingGrid and orientation
% if valid, break
% else, issue statment (and the big while loop continues)
end
Tariq Hammoudeh
2021년 12월 30일
Im sorry i realized i wasnt too clear, those 'specific numbers" are just grid numbers where if you choose v or h on them the ship will be placed out of bounds, so what my actual code is:
disp(' You will now place your corvette (1X2) ship')
startingGrid= input(' Please choose the grid number you want your ship to start in : ');
% orientation= input(' Please enter v if you want your ship to be placed vertically or h if you want it horizontally', 's');
if startingGrid == 1
while true
orientation = input(' Please enter v if you want your ship to be placed vertically or h if you want it horizontally', 's');
if ismember(orientation,{'v' 'h'})
break;
end
disp(' please choose v or h only and make sure to use small letters ');
end
if strcmp(orientation,'v')
...
else
...
end
elseif startingGrid == 2
.. repeat the same code above but do different v and h stuff..
elseif startingGrid == 3
.....
So what i need for example is when startingGrid == 6
if startingGrid == 6
while true
orientation = input(' Please enter v if you want your ship to be placed vertically or h if you want it horizontally', 's');
if ismember(orientation,{'v' 'h'})
break;
end
disp(' please choose v or h only and make sure to use small letters ');
end
if strcmp(orientation,'v')
..
else
display ('ship will be out of bounds please try again') and let the user try again
end.
because here when its h and starting grid 6 the ship will be out of bounds
Note: Im very well aware this isnt the most convenient way as ill have a over a 100 if statements, and ill have to go through each one individually, but its the only way i can think of.
Voss
2021년 12월 31일
If you can think of a way to combine orientation, startingGrid, the size of the grid, and the size of the ship into one or a few conditions to check, you'll be much better off and have many fewer if statements. For example:
grid_size = 6;
ship_size = 2;
startingGrid = 5;
orientation = 'h';
if startingGrid+ship_size-1 > grid_size
disp('that''s a problem');
else
disp('that''s ok');
end
that's ok
grid_size = 6;
ship_size = 2;
startingGrid = 6;
orientation = 'h';
if startingGrid+ship_size-1 > grid_size
disp('that''s a problem');
else
disp('that''s ok');
end
that's a problem
grid_size = 6;
ship_size = 3;
startingGrid = 5;
orientation = 'h';
if startingGrid+ship_size-1 > grid_size
disp('that''s a problem');
else
disp('that''s ok');
end
that's a problem
Tariq Hammoudeh
2022년 1월 2일
편집: Tariq Hammoudeh
2022년 1월 2일
@Benjamin Thank you but, if the user enters 7 and h, then the above code wont let him, even though it should, so is there a way to fix it.
I tried:
while orientation=='h' && startingGrid==6 || orientation=='h' && startingGrid==12 % and so on for all conditions that will result in out of bounds
disp('Your ship will be placed out of bounds ')
startingGrid=input('Enter a grid number you want your ship to start in again : ');
orientation=input('Please enter v if you want your ship to be placed vertically or h if you want it horizontally : ','s');
end
and it works, but then for the bigger ships this line would get tooo long, so is there a way to fix the previous code so i can use something like
while orientation =='h' && startingGrid+shipSize-1 > bs
...
end
instead of the very long line
Voss
2022년 1월 2일
I would do it something like this. It doesn't check that ships don't overlap with each other, but it does check that each ship is on the board completely. I believe it has the structure you are looking for.
This code uses a 6-by-6 board, and assumes the definition of startingGrid is as follows: startingGrid = 1, 2, 3, 4, 5, 6 corresponds to the top row of the board, 7 is second row, first column, etc. (which is implied by your code). (Because this indexing is the opposite of how MATLAB does linear indexing in 2d matrices, it is convenient to build the transpose of the user-specified board and then transpose it at the end to get the final result.)
grid_size = 6;
board = zeros(grid_size);
ship_sizes = [2 3 5];
for i = 1:numel(ship_sizes)
while true
while true
startingGrid = input(' Please choose the grid number you want your ship to start in : ');
% validate startingGrid with your other code here
if startingGrid >= 1 && startingGrid <= grid_size^2
break
end
disp('please try again');
end
while true
orientation = input(' Please enter v if you want your ship to be placed vertically or h if you want it horizontally', 's');
if ismember(orientation,{'v' 'h'})
break
end
disp(' please choose v or h only and make sure to use small letters ');
end
% check consistency between startingGrid and orientation
n_max = grid_size-ship_sizes(i)+1;
if strcmp(orientation,'h')
if mod(startingGrid-1,grid_size)+1 > n_max
disp('Your ship will be placed out of bounds (off the right side of the board)');
continue
end
% if valid, place the ship ...
board(startingGrid+(0:ship_sizes(i)-1)) = i;
else
if floor((startingGrid-1)/grid_size)+1 > n_max
disp('Your ship will be placed out of bounds (off the bottom of the board)');
continue
end
% if valid, place the ship ...
board(startingGrid+grid_size*(0:ship_sizes(i)-1)) = i;
end
% ... and break
break
end
end
board = board.';
disp(board);
Tariq Hammoudeh
2022년 1월 2일
편집: Tariq Hammoudeh
2022년 1월 2일
@Benjamin Again thank you i added this to my other code and it works fine, but i just want to ask what does the for loop do, I understood everything else but i just want to know what does this for loop do.
Voss
2022년 1월 2일
The for loop is to loop over the different ships, asking the user for each ship's startingGrid and orientation and placing each ship on the board.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Environment and Settings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
아시아 태평양
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)