1

I have the following example which expresses the type of problem that I'm trying to solve:

clear all
textdata = {'DateTime','St','uSt','Ln','W'};
data = rand(365,4);
Final = struct('data',data,'textdata',{textdata})
clear textdata data

From this, Final.data contains values which correspond to the headings in Final.textdata excluding the first ('DateTime') thus Final.data(:,1) corresponds to the heading 'St'... and so on. What I'm trying to do is to create a variable in the workspace for each of these vectors. So, I would have a variable for St, uSt, Ln, and W in the workspace with the corresponding values given in Final.data.

How could this be done?

2 Answers 2

3

Will this solve your problem:

    for ii=2:length( textdata )
      assignin('base',Final.textdata{ii},Final.data(:,ii-1));
    end

Let me know if I misunderstood.

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

1 Comment

It is kind of what I was looking for, but the data that I have is stored in a structure, similar to 'Final' above (question amended).
2

The direct answer to your question is to use the assignin function, like so (edit: just like macduff suggested 10 minutes ago):

%Starting with a Final structure containing the data, like this
Final.textdata = {'DateTime','St','uSt','Ln','W'};
Final.data = rand(365,4);

for ix = 1:4
    assignin('base',Final.textdata{ix+1}, Final.data(:,ix));
end

However, I strongly discourage using dynamic variable names to encode data like this. Code that starts this way usually ends up as spaghetti code full of long string concatenations and eval statements. Better is to use a structure, like this

for ix = 1:4
    dataValues(Final.textdata{ix+1}) = Final.data(:,ix);
end

Or, to get the same result in a single line:

dataValues = cell2struct(num2cell(Final.data,1), Final.textdata(2:end),2)

1 Comment

great method, but as stated above the data is originally in a structure so how would I apply this to my data (see amended question), i.e. how do I get to the different cells in textdata?

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.