Pregunta

In MATLAB, I really need someones expertise. I have a csv file like the following (extra spaces is just to make it readable):

State,   Damage,    Blizzards,
Texas,   2,         2,
Alabama, 1,         0,
Alabama, 0,         1,
Texas,   5,         3,
Montana, 0,         8,
Arizona, 0,         0,
Arizona, 0,         1,
Texas,   8,         5,

I have applied textread and strcmpi. Here is the goal: I need to develop a loop that gets each individual state with the associated data with the state and plot it on one plot, and repeats for each state until finish. So for loop one: Alabama has two data sets, so I need this extracted and plotted. Loop two: Texas has 3 data sets so I need this extracted and plotted. And the process repeats until all the states have been applied.

Here is the code:

filename = 'datacollect.csv'
[State,Damage,Blizzards] = ...
textread(filename,'%s %d... %d','delimiter',',','headerlines',1);
index1 = strcmpi(State, 'Texas');
Damage = Damage(index1)
Blizzards = Blizzards(index1)
plot(Damage,Blizzards) %for Texas

Trying to make it a loop, automatic, so I don't have to hard code it.

I really need a solution -- even if you are unsure.

¿Fue útil?

Solución

Amro's answer should definitely point you in the right direction, but here's the full solution spelt out for you, in case you're still having trouble:

%// 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

The resulting S is an array of structs with the fields state, damage and blizzards.

Now you can loop over this array of structs, accessing fields of the corresponding struct in each iteration. For instance, to access the damage values of Alabama (the second struct), you can do S(2).damage.

Hope this helps!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top