1
votes

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:

  • a = 1
  • a_2 = 2
  • a_3 = 3

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

2
Yeah it's already loaded. I mean I could force the load in the function before I call the who function. - Lemming_87
I would suggest reading doc who at least once thoroughly if you haven't before. I could see the solution right there. - Divakar
@Divakar Forcing the load of the MATLAB file within the function seams to work, thanks for that. But you would think that using the location parameter, would be enough. Thanks again, much appreciated. - Lemming_87
@Divakar I now know what I was doing wrong, this: disp(who('brain10*','Results_v2')); sould have been like this: disp(who('brain10*','-file','Results_v2'));. it works fine now, thanks for that. You learn something new everyday/night. - Lemming_87
Awesome! But there's a reason why function uses encapsulation and as such file loading inside function must be avoided. Daniel's suggestion makes sense in that aspect. - Divakar

2 Answers

1
votes

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')

0
votes

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.