5

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.

4
  • I have seen in forums people saying that you can do that using EVAL, but I don't know how. Commented Apr 30, 2015 at 3:16
  • 1
    See stackoverflow.com/questions/1823668/…. Write a little function that uses fieldnames and assignin to assign them in to your workspace. Commented Apr 30, 2015 at 3:18
  • 1
    Good to know, but also sad that Matlab doesn't support this! Commented Apr 30, 2015 at 3:22
  • FYI the use of eval for this is now discouraged by Mathworks in favour of dynamic fieldnames (as used in Andrew's answer) blogs.mathworks.com/loren/2005/12/13/… Commented Apr 30, 2015 at 9:32

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Here's a oneliner using cellfun:

myvar=structWithVariables; %for readability of code =)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.