How to limit user to only inputting matrices
Show older comments
I'm trying to create a script that will invert matrices for me, but I want it to limit the input from the user to only allow them to input matrices. This is the section I'm having problems with:
M=input('input matrix: ');
if length(M)~= size(M,1)
input('Must input a square matrix: ')
if ismatrix(M) == 0
input('Must input matrix: ')
end
end
I tried to use the ismatrix function (if it is not a matrix it should produce a false which is 0); however, the code doesn't even get to that point as there is an error 'Undefined function or variable' right from the input. For example, if the user were to type in 'hi' I get the matlab error rather than 'Must input matrix' like I wanted. How can I limit the user to only inputting matrices?
Answers (1)
Geoff Hayes
on 13 Feb 2017
isaiah - the input function treats the input as if it were an expression. That is why you get an error with
>> M=input('input matrix: ');
input matrix: hi
Error using input
Undefined function or variable 'hi'.
whereas something like
>> M=input('input matrix: ');
input matrix: [1 2; 3 4]
works as I have entered the expression to create a 2x2 matrix with specific variables. If you wish to not fail immediately, you could add the 's' switch to your call to input so that the expression is not evaluated but it will be treated as a string...which means you would have to come up with a way for the user to enter a string that would represent a matrix. See https://www.mathworks.com/matlabcentral/answers/167375-how-to-convert-string-to-matrix for an idea.
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!