Reputation: 5953
I have written a function that takes the names and values of the input variables and writes them to a file. eg.
a = 10;
b = 100;
writevars('file.txt',a,b);
gives me a file file.txt
that contains:
\def\a{\num{10}}
\def\b{\num{100}}
It would now like to be able to pass on all variables that are found using the who
command. Eg if who
returns:
a b z
I would like to be able to use writevars
as if I called writers('file.txt', a, b, z)
.
The main problem I have is that writevars makes use of inputname
... (temporary variables won't work e.g. writevars('file.txt', 100)
doesn't work since there is no name to be given in the file).
var_names = who;
for i = 1 : length(var_names)
evalin('caller',['writevars(''file.txt'', ' char(var_names(i)) ' )']);
end
Upvotes: 2
Views: 153
Reputation: 74940
You can use EVALIN to run who
from within writevars
, e.g.
function writevars(filename,varargin)
%# get a list of variable names in the calling workspace and read their values
if isempty(varargin)
listOfVars = evalin('caller','who');
values = cell(size(listOfVars));
for i=1:length(listOfVars)
values{i} = evalin('caller',listOfVars{i});
end
else
%# use inputname to read the variable names into listOfVars
end
%# --- rest of writevars is here ---
Upvotes: 3
Reputation: 20915
It can be used by using the return value of whos command:
function GetAllVars
a = 45;
x = 67;
ff = 156;
z = who();
for i=1:numel(z)
if ~isequal(z{i},'z')
fprintf(1,'%s = %f\n',z{i},eval(z{i}));
end
end
Upvotes: 0