How to load variables from a structure into a Matlab workspace?

Suppose I have access to a structure created using a function load:

structWithVariables = load('data.mat');

I want to load all the variables from this structure into the workspace, but I cannot find a way to do this without hard-coding the names of all the variables.

Note. I do not have access to the .mat file, as well as to the code that loads the structure, I really only have the structure.

Note 2: the reason I want to do this is to simply use code that refers to the variables as if they were in the workspace. I do not want to change the code.

+4
source share
2 answers

. fieldnames, assignin, .

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

struct2vars(structWithVariables), .

, , , , .

+6

oneliner cellfun:

myvar=structWithVariables; %for readability of code =)

cellfun(@(x,y) assignin('base',x,y),fieldnames(myvar),struct2cell(myvar));
0

All Articles