MATLAB: The validateMap function takes one parameter, matrix, and determines if
ID: 3731052 • Letter: M
Question
MATLAB: The validateMap function takes one parameter, matrix, and determines if matrix is a valid map for the bug hop problem. You may assume that the values in matrix are integers.
The first line of your validateMap function should be:
In order to be valid, a map must be a row vector containing at least three values, the values must only be 0's and 1's, the first and last values in the vector must be 0, and the second and second-to-last values in the vector must be 1. The validateMap function should return 1 (i.e., true) if matrix is a valid map and 0 (i.e., false) if matrix is not a valid map. Additionally, if matrix is not a valid map, the function should display one of the following error messages:
- if matrix is not a row vector, the error message should be: map must be a row vector
- if matrix does not contain at least 3 values, the error message should be: map must contain at least 3 values
- if the values are not all 0's and 1's, the error message should be: map may only contain the values 0 and 1
(Hint: consider max and min)
- if the first and last values are not 0, the error message should be: map must begin and end with 0
- if the second and second-to-last values are not 1, the error message should be: 2nd and 2nd-to-last map values must be 1
The error messages must be exactly as indicated above. If matrix is not valid for multiple reasons, your validateMap function should display just one error message: the first one that applies in the list above (considered from top to bottom). For example:
validateMap([ 0 1 2 3 ]) should return the value 0 and display the error message map may only contain the values 0 and 1
validateMap([ -7 3 ]) should return the value 0 and display the error message map must contain at least 3 values
validateMap([ 0 1 0 ]) should return the value 1 (and should not display any messages)
Explanation / Answer
function isValid = validateMap(matrix)
s=size(matrix);
if s(1)~=1
isValid=0;
disp('map must be a row vector')
elseif length(matrix)<3
isValid=0;
disp('map must contain at least 3 values')
elseif min(matrix)~=0 || max(matrix)~=1
isValid=0;
disp('map may only contain the values 0 and 1')
elseif matrix(1)~=0 || matrix(end)~=0
isValid=0;
disp('map must begin and end with 0')
elseif matrix(2)~=1 || matrix(end-1)~=1
isValid=0;
disp('2nd and 2nd-to-last map values must be 1')
else
isValid=1;
end
OUTPUT:
validateMap([0 1 2 3 ])
map may only contain the values 0 and 1
ans =
0
validateMap([ 7 3 ])
map must contain at least 3 values
ans =
0
validateMap([ 0 1 0 ])
ans =
1
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.