matlab how to iterate through all objects in a workspace

14,061

Solution 1

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

Solution 2

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
Share:
14,061
jhlu87
Author by

jhlu87

Trader learning to program

Updated on July 20, 2022

Comments

  • jhlu87
    jhlu87 almost 2 years

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