Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load variables from struct into Matlab workspace?

Tags:

matlab

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.

like image 819
hsgubert Avatar asked Jan 09 '23 11:01

hsgubert


2 Answers

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.

like image 73
Andrew Janke Avatar answered Jan 15 '23 12:01

Andrew Janke


Here's a oneliner using cellfun:

myvar=structWithVariables; %for readability of code =)

cellfun(@(x,y) assignin('base',x,y),fieldnames(myvar),struct2cell(myvar));
like image 45
user2305193 Avatar answered Jan 15 '23 12:01

user2305193