Suppose I have access to a struct that was created using the load
function:
structWithVariables = load('data.mat');
I want to load all the variables from this struct into workspace, but I cannot find any way of doing that without hardcoding the names of all variables.
Note: I don't have access to the .mat file, nor the code that loads the struct, I really only have the struct.
Note 2: the reason I want to do that is just to use some code that references the variables as if they are in the workspace. I don't want to change the code.
Yep. Use fieldnames
to get at the variable names programmatically, and assignin
to stick them in your workspace.
function struct2vars(s)
%STRUCT2VARS Extract values from struct fields to workspace variables
names = fieldnames(s);
for i = 1:numel(names)
assignin('caller', names{i}, s.(names{i}));
end
Call that function as struct2vars(structWithVariables)
, and now they're populated in to your workspace as variables.
Though if you have access to the code you want to call, it might be cleaner to rewrite that to take the variables as function arguments instead of looking in the current workspace.
Here's a oneliner using cellfun
:
myvar=structWithVariables; %for readability of code =)
cellfun(@(x,y) assignin('base',x,y),fieldnames(myvar),struct2cell(myvar));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With