How do I use the who command within a function

8 次查看(过去 30 天)
I am trying to use the who command within a function to make a list of the variables in the current workspace that match a given string.
Here is my little test function to get this portion working. In my case there are 6 variables that match the string so test should return "6". However, I always get 0. If I comment out the function line and run it as a script, it works fine. Is there a way to get the who command within a function to generate a list of variables from the current workspace?
function[test] = myfun()
%dev = 'R_A_bot';
%keys = strcat('IV','*',dev,'*');
vars = who ('IV*R_A_bot*');
test = length(vars);
Thank you.

采纳的回答

Matt Fig
Matt Fig 2012-9-7
编辑:Matt Fig 2012-9-7
When a function is running, the current workspace is the workspace of the function. That is just how it works.
Why not just keep it as a script?
If you must have a function for some reason, you can use this line, with either 'caller' or 'base' depending.
vars = evalin('caller','who (''IV*R_A_bot*'')');
  1 个评论
Becca
Becca 2012-9-7
Thank you, that worked.
That was just a snippet of code I wrote trying to solve the problem. I have several different scripts that I change a little here, a little there for each run. I am making each a function so I can choose which "scripts" to call and only have to change one thing and pass it through.
For example, in that one I will eventually pass in dev and assemble "keys" to use as the expression in who. Dev could be passed into say the 4 functions I run on that dataset.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Variables 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by