Minimalist
Minimalist

Reputation: 975

Matlab: Series of Variables in a Loop

This is a solution from another stackoverflow participant who helped me out. Data is coming from a csv file:

    States Damage Blizzards

    Indiana 1      3
    Alabama 2      3
    Ohio    3      2
    Alabama 4      2


%// Parse CSV file
[States, Damage, Blizzards] = textread(csvfilename, '%s %d %d', ...
    'delimiter', ',', 'headerlines', 1);

%// Parse data and store in an array of structs
[U, ix, iu] = unique(States);        %// Find unique state names
S = struct('state', U);              %// Create a struct for each state
for k = 1:numel(U)
    idx = (iu == k);                 %// Indices of rows matching current state
    S(k).damage = Damage(idx);       %// Add damage information
    S(k).blizzards = Blizzards(idx); %// Add blizards information
end

In MATLAB, I need to create a series of assigned variables (A1,A2,A3) in a loop. So I have structure S with 3 fields: state, tornado, hurricane.

Now I have attempted this method to assign A1 =, A2 =, which I got an error because it will not work for structures:

   for n = 1:numel(S)
   eval(sprintf('A%d = [1:n]',S(n).states));
   end

Output goal is a series of assigned variables in the loop to the fields of the structure:

  A1 = 2 3
  A2 = 2 3
  A3 = 4 5

Upvotes: 0

Views: 875

Answers (1)

Schorsch
Schorsch

Reputation: 7895

I'm not 100% sure I understand your question.
But maybe you are looking for something like this:

for n = 1:numel(S)
   eval(sprintf('A%d = [S(n).damage S(n).blizzards]',n));
end

BTW using evalc instead of eval will suppress the command line output.

A little explanation, why

eval(sprintf('A%d = [1:n]',S(n).state));  

does not work:

S(1).state  

returns

ans = 
   Alabama

which is a string. However,

A%d

expects a number (see this for number formatting).
Additionally,

numel(S) 

yields

ans = 
   3

Therefore,

eval(sprintf('A%d = [1:n]',n));

will simply return the following output:

A1 =

 1

A2 =

 1     2

A3 =

 1     2     3  

Hence, you want n as a counter for the variable name, but compose the vector of the entries in the other struct-fields (damage and blizzards), again, using n as a counter.

Upvotes: 1

Related Questions