No errors, switch case won't identify correctly
조회 수: 2 (최근 30일)
이전 댓글 표시
When I input P as 1, this runs correctly and assigns the correct R value. When P is 2 (or any other number) the R value is incorectly set to 9 and I'm not sure why.
fprintf('Please enter the number of rows in the array: \n')
M = input('Rows: ');
fprintf('Please enter the number of columns in the array: \n')
N = input('Rows: ');
fprintf('Please enter the number corresponding to the cell of interest: \n')
P = input('Cell: ');
switch(P)
case P <= M
if P == 1 %% Top left corner
R = 1; %% R is an identifier that will be used to identify P as belonging to a certain wall, corner, or in the middle
%% R for corners is 1-4, R for walls is 5-6
elseif (P > 1 && P < M) %% Left Wall
R = 5;
elseif P == M %% Bottom left corner
R = 2;
end
case (P <= (N*M) && P > M)
if P == (N*M) %% Bottom right corner
R = 3;
elseif mod(P, M) == 0 && P ~=M && P ~= (N*M) %% Bottom wall
R = 6;
elseif mod(P, M) == 1 && P ~=1 && P ~= ((N*M)-(M-1)) %% Top wall
R = 7;
elseif P == ((N*M)-(M-1)) %% Top right corner
R = 4;
elseif P > ((N*M)-(M-1)) && P < (N*M) %% Right wall
R = 8;
end
otherwise
R = 9;
end
댓글 수: 0
답변 (1개)
Cris LaPierre
2023년 1월 28일
편집: Cris LaPierre
2023년 1월 28일
The issue is with the line switch(P)
Switch looks for a case that matches the value of P, but you case statements return logical (0 or 1), while P is a numeric value between 1 and m*n. The only time this will work is when P is 1, as in that condition, one of the case statements evaluates to true, or 1.
For what you are doing, I think you should leave the case stamements as they are, and change the switch value to true. That way, it will look for and execute the first case that is true.
fprintf('Please enter the number of rows in the array: \n')
M = input('Rows: ');
fprintf('Please enter the number of columns in the array: \n')
N = input('Rows: ');
fprintf('Please enter the number corresponding to the cell of interest: \n')
P = input('Cell: ');
switch true % <----------Change made here
case P <= M
if P == 1 %% Top left corner
R = 1; %% R is an identifier that will be used to identify P as belonging to a certain wall, corner, or in the middle
%% R for corners is 1-4, R for walls is 5-6
elseif (P > 1 && P < M) %% Left Wall
R = 5;
elseif P == M %% Bottom left corner
R = 2;
end
case (P <= (N*M) && P > M)
if P == (N*M) %% Bottom right corner
R = 3;
elseif mod(P, M) == 0 && P ~=M && P ~= (N*M) %% Bottom wall
R = 6;
elseif mod(P, M) == 1 && P ~=1 && P ~= ((N*M)-(M-1)) %% Top wall
R = 7;
elseif P == ((N*M)-(M-1)) %% Top right corner
R = 4;
elseif P > ((N*M)-(M-1)) && P < (N*M) %% Right wall
R = 8;
end
otherwise
R = 9;
end
참고 항목
카테고리
Help Center 및 File Exchange에서 Calculus에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!