How can I overcome 'Error: Undefined function or variable 'k'.' to check for a valid input?
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I'm trying to write a code that will not output any errors but will define the errors in itself. Say if someone enters test(spaghetti, meatballs) (or 15pies, @%FAd, anything that isn't a number) I want to be able to address the problem in the function. What happens is matlab detects the error, breaks the function, and outputs the error message. I've tried exist(), isscalar(), isnumeric(), isnan(), etc. What am I missing here?
Example code
Function product = test(x ,y)
if exist(x) && exist(y)
product = x * y
else
disp('Please enter numerical values')
end
end
If someone enters test(spaghetti, meatballs) The output should say "Please enter numerical values." What it does say is: "Error: Undefined function or variable 'spaghetti'."
It works correctly if I enter test(6, 8) or even test(spaghetti, meatballs) if both terms are predefined as numbers.
0 comentarios
Respuestas (1)
Star Strider
el 11 de Nov. de 2016
The ischar function is probably what you want. I created a cell array and used cellfun here to demonstrate. You can test ‘x’ and ‘y’ separately with ischar.
Example:
cv = {rand, '15pies', randi(9), 'spaghetti', randn, '@%FAd'};
check = cellfun(@ischar, cv)
check =
1×6 logical array
0 1 0 1 0 1
2 comentarios
Star Strider
el 11 de Nov. de 2016
You need to test to be certain it is not a character, so use the tilde (~) to logically negate the results. Also, single quotes create string or character variables, so eliminate the quotes as well:
if ~ischar(x) && ~ischar(y)
That should do what you want.
Also, you have to assign something to ‘spaghetti’ for it to work in your code:
spaghetti = 20; % Numeric Variable
spaghetti = 'pasta'; % Character Variable
You may also need to test for cells, tables, structures, and others if you expect they could be passed as variables. Otherwise, they would all throw errors and return control to your Command Window rather than continuing to execute your code.
Ver también
Categorías
Más información sobre Response Computation and Visualization en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!