No errors, switch case won't identify correctly
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Cris LaPierre
am 28 Jan. 2023
Bearbeitet: Cris LaPierre
am 28 Jan. 2023
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
Siehe auch
Kategorien
Mehr zu Entering Commands finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!