Matlab: Series of Variables in a Loop -


this solution stackoverflow participant helped me out. data coming 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 , store in array of structs [u, ix, iu] = unique(states);        %// find unique state names s = struct('state', u);              %// create struct each state 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, need create series of assigned variables (a1,a2,a3) in loop. have structure s 3 fields: state, tornado, hurricane.

now have attempted method assign a1 =, a2 =, got error because not work structures:

   n = 1:numel(s)    eval(sprintf('a%d = [1:n]',s(n).states));    end 

output goal series of assigned variables in loop fields of structure:

  a1 = 2 3   a2 = 2 3   a3 = 4 5 

i'm not 100% sure understand question.
maybe looking this:

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

btw using evalc instead of eval suppress 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 string. however,

a%d 

expects number (see this number formatting).
additionally,

numel(s)  

yields

ans =     3 

therefore,

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

will return following output:

a1 =   1  a2 =   1     2  a3 =   1     2     3   

hence, want n counter variable name, compose vector of entries in other struct-fields (damage , blizzards), again, using n counter.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -