# Why is "undefined" a variable that I have previously defined???

13 views (last 30 days)

Show older comments

Hello, I use a variable 'd' in a function F, such that this variable 'd' is defined as an input of this function F. In F, 'd' is used only in a sub-function G, where acts as an input of G. However, if I ask for the value of 'd' in F, there is no problem to get it, while Matlab says me that 'd' is "undefined" when it tries to use it in G. Does someone knows why? Thank you in advance for your help.

Ad'

##### 0 Comments

### Answers (3)

Matt J
on 5 Jul 2013

##### 2 Comments

Matt J
on 5 Jul 2013

Edited: Matt J
on 5 Jul 2013

You need to show more. My guess is that you passed too few arguments to G() by mistake. For example, if d is defined as the final of 5 input arguments to G()

function output = G(arg1, arg2, arg3, arg4, d)

....

but you only passed 4 arguments to G() when computing W,

W=G(a,b,c d);

then G() will not be able to find d in its workspace. You could use NARGIN to investigate this.

Guru
on 5 Jul 2013

or future reference, putting a little MATLAB code down makes things a lot more clear than trying to explain it with words, especially if your English is not of similar level to the other readers who would like to help you with an answer.

I am guessing you have something that looks like this:

function F(d)

% So d is an input to function F.

% Some random pieces of code

disp(d) % works and displays d

y = G; % undefined error because d is not defined

function y = G(d)

The short answer is that subfunctions have different workspaces as they are functions themselves, just happen to live in the same file as another funciton. Every function/subfunction/private function in MATLAB have their own workspace (memory set aside just for their use). The "shared" workspaces in MATLAB is the global workspace (free to any that declares a link to the global workspace and nested workspace (limited with various rules one of which is the same file)

The typical way we communicated between workspaces is by passing inputs and asking for outputs. So to fix your problem, do this instead (using my above dummy functions

function F(d)

% So d is an input to function F.

% Some random pieces of code

disp(d) % works and displays d

y = G(d);

% Now works because we provide a value for the 'd' in G's workspace which is a

% copy of the 'd' in F's workspace. They will have the same value but are not

% linked, ie if 'd' changes value in G's workspace, the change will not go back

% to the 'd' in F's workspace.

function y = G(d)

##### 2 Comments

Danielle Klawitter
on 21 Feb 2018

John D'Errico
on 21 Feb 2018

### See Also

### Categories

### Products

### Community Treasure Hunt

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

Start Hunting!