How can I overcome 'Error: Undefined function or variable 'k'.' to check for a valid input?

4 Ansichten (letzte 30 Tage)
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.

Antworten (1)

Star Strider
Star Strider am 11 Nov. 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 Kommentare
Lewis Wooler
Lewis Wooler am 11 Nov. 2016
I can see where that could be useful but I'm still getting the same results
the code
function product = test(x ,y)
if ischar('x') && ischar('y')
product = x * y;
else
disp('Please enter numerical values')
end
end
still result in
test(spaghetti,7)
Undefined function or variable 'spaghetti'
I think this might just be an issue with Matlab itself
Star Strider
Star Strider am 11 Nov. 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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Response Computation and Visualization finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by