Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

why matlab give me a message "Undefined function or variable"?

3,317 views
Skip to first unread message

Yu Cheong Kim

unread,
Sep 1, 2009, 10:47:04 PM9/1/09
to
first, i loaded a variable in command window.
for example: write down "y=1;" in command window.

next, called the function below
-----below-----
function x=test(number)
x=y+number;
end
------------------

and then, input "test(1)" in command window.
(i already set the path of test.m file)

i expected matlab give me the answer "2".
but it gives me a following message
=============================
??? Undefined function or variable "y".
=============================

why's that? i already load variable "y".
how can i fix it to work?

Matt Fig

unread,
Sep 2, 2009, 1:09:02 AM9/2/09
to
Function M-Files have their own workspace that differs from the base workspace. That is why you must pass arguments into a function! If you want y to be hardcoded into the function, do this:

function x = test(number)
y = 1;
x = y + number;

Now call the function as you did before.
If you want to be able to use different values of y in your function, do this:

function x = test(y,number)
x = y + number;

Now call the function like this:

>>y = 1;
>>x = test(y,1)


You may also want to look at the results of:

>>docsearch('scope of a variable')

Yu Cheong Kim

unread,
Sep 2, 2009, 4:24:02 AM9/2/09
to
to.matt

first of all, i appreciate helping me.
your comment is perfect!

it gives me a big hint to solve my problem.
i'm considering whether or not using "global" command at test.m file.

yours sincerely,
Yu cheong.

"Matt Fig" <spam...@yahoo.com> wrote in message <h7kule$g6k$1...@fred.mathworks.com>...

Andy

unread,
Sep 2, 2009, 9:04:04 AM9/2/09
to
"Yu Cheong Kim" <yusti...@naver.com> wrote in message <h7la32$hso$1...@fred.mathworks.com>...

> to.matt
>
> first of all, i appreciate helping me.
> your comment is perfect!
>
> it gives me a big hint to solve my problem.
> i'm considering whether or not using "global" command at test.m file.
>
> yours sincerely,
> Yu cheong.
>

% It sounds like in your situation you might be better off passing y as an optional
% parameter to your function:

function x=test(number,varargin)
if nargin==2
y=varargin{1};
else
y=1; % set a default value for y
end
x=y+number;
end

%{
% Sample output
>> test(1)
ans =
2
>> test(1,2)
ans =
3
%}

0 new messages