Lemming_87
Lemming_87

Reputation: 13

Using function "Who" within a function in MATLAB

I am using Matlab R2013a and I am trying to use the 'who' function within a function to retrieve a list of variables that begin with a name.

Let's say I have a list of variable in my workspace as follows:

when I run this:

who('a*');

it works fine.

But when I run the same thing inside a function like this:

function someFunction()

   who('a*');

end

or

function someFunction()

   disp(who('a*'));

end

It doesn't. No error, just no output.

If I had saved those variables in a Matlab file called

myVariables.mat

and run this within the same function like so:

function someFunction()

   who('a*','myVariables');

end

It still doesn't work.

I can understand why the first might not work because of scope, but specifying the file to run the 'who' function on should work... what am I missing?

Any help would be appreciated.


Regards

Diaa

Upvotes: 1

Views: 428

Answers (2)

Jonas
Jonas

Reputation: 74940

As mentioned by @Daniel, the workspace of a function is separate from the base workspace. There are two ways you could use who inside a m-file to inspect the base workspace:

  1. Use a script instead of a function (i.e. omit the function- line; launch the script by its file name as you do with a function): A script shares the base workspace, and thus, who will be able to see all your variables.

  2. Use evalin: evalin('base','who')

Upvotes: 1

Daniel
Daniel

Reputation: 36720

You are trying to access variables within a function. Only the input arguments and global variables are visible within a function. You have to do something like:

function someFunction(a1,a2)

   who('a*');

end

If you are really trying to use dynamic variable names, I would strongly recommend to change your design.

Upvotes: 0

Related Questions