Error undefined variable or method in script
Show older comments
i don't understand why am i getting this error
i am using matlab online.
clear
clc
my_num = randi(30);
x = input('Enter a number : \n');
guess_the_number(x);
function guess_the_number(n)
if n == my_num
fprintf('Well you guessed it , %d.\n', a)
elseif n > 30
fprintf('Too Large bud, wanna go smaller maybe')
else
fprintf('Not correct, but nice try, number was %d', a)
end
end
Error is this
Enter a number :
12
Unrecognized function or variable 'my_num'.
Error in guess_the_number>guess (line 10)
if n == my_num
Error in guess_the_number (line 6)
guess(x);
Answers (1)
Ameer Hamza
on 20 May 2020
Edited: Ameer Hamza
on 20 May 2020
You need to pass the value of 'a' and 'myNum' to the function
clear
clc
my_num = randi(30);
x = input('Enter a number : \n');
a = 2;
guess_the_number(x, my_num, a);
function guess_the_number(n, my_num, a)
if n == my_num
fprintf('Well you guessed it , %d.\n', a)
elseif n > 30
fprintf('Too Large bud, wanna go smaller maybe')
else
fprintf('Not correct, but nice try, number was %d', a)
end
end
An alternative is to use nested functions.
Categories
Find more on Get Started with MATLAB 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!