0

Suppose we have loaded data into cell array:

DATA={'foo',[1,5];'bar',[2,6]}

Is there way how to declare variables named by 1st column in DATA with content of 2nd column?

2 Answers 2

5

You can do that using eval

for ii = 1:size(DATA,1)
    eval( [DATA{ii,1}, ' = ', num2str( DATA{ii,2} )] );
end

However, use of eval is not recommended.

You can use dynamic field names instead:

s = cell2struct( DATA(:,2), DATA(:,1), 2 );
Sign up to request clarification or add additional context in comments.

2 Comments

this won't cover cases where the variable is not a vector, such as a ND matrix (or even a 2D matrix), cell array, structs, etc
@carandraug you are right. I used num2str instead of my personal favorite sprintf just to cover simple vectors. But eval has indeed limitations here. Maybe combined with disp? I prefer struct with dynamic names...
1

There's an assignin function which takes a variable name and assign to it a specific value:

for r = 1:size (DATA, 1)
  assignin ('caller', DATA{r,:});
end

2 Comments

this will not work in a function. or worse, it will work with unexpected results: variables will be assigned in 'base' instead of in the context of the function :O
@Shai ups! You're correct. I misunderstood base and caller, I thought caller was 1 level down in the stack, and base the current scope.

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.