Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlab how to iterate through all objects in a workspace

I have a matlab workspace where all of the variables are loaded from a .mat file using the load command. Now, I want to iterate through all of these objects and perform operations on them.

Is there someway to access the objects without explicitly stating their names? For example workspace(1)?

like image 780
jhlu87 Avatar asked Aug 26 '11 18:08

jhlu87


2 Answers

You can get the list of all the variables as string using who:

myvars = who;

then if you want to do something with the content of the variables (who gives variable names only), you can do something like this:

for i=1:length(myvars)
    myfunction(eval(myvars(i)))
end
like image 68
Simon Avatar answered Sep 27 '22 17:09

Simon


I agree with @Simon's answer, however if all you are interested in are variables that are loaded from a single .mat file, you may be better off using the struct-assignment form of load:

S = load('myfile.mat')

Now instead of getting 'x', 'y', 'z' in your workspace, you have S.x, S.y and S.z.

You can then iterate all the fields of the struct with:

for f = fieldnames(S)'
   disp(['Field named: ' f{1} ]);
   disp('Has value ')
   disp(S.(f{1}));
end
like image 29
Lambdageek Avatar answered Sep 27 '22 15:09

Lambdageek