Search code examples
matlabcsvmat-file

Save variable from .mat into a different column of CSV


I have a .mat file with a bunch of variables (cells). They are actually just a column vector of doubles.

Sample of what the .mat file looks like. The actual one has more files

Name                Size             Bytes  Class    Attributes

  r2_Fall_1997        1x1                144  cell
  r2_Fall_1998        1x8               1152  cell
  r2_Fall_1999        1x325            46800  cell
  r2_Fall_2000        1x368            52992  cell

  r2_Spring_1997      1x1                144  cell
  r2_Spring_1998      1x8               1152  cell
  r2_Spring_1999      1x325            46800  cell
  r2_Spring_2000      1x368            52992  cell

  r2_Spring_2014      1x1                144  cell
  r2_Summer_1997      1x1                144  cell
  r2_Summer_1998      1x8               1152  cell
  r2_Summer_1999      1x325            46800  cell
  r2_Summer_2000      1x368            52992  cell

I want to save each season (so r2_Spring_, r2_Summer_, r2_Fall*) into a CSV file with each year being a different column.

I am using the following code right now, but it's creating a CSV file for each variable, but not actually saving anything - it's 0 bytes. How can I make each iteration of the inner loop save into a new column of the CSV file?

load Correlation_PM25_24hr_O3_MDA8

Seasons = {'Spring'; 'Summer'; 'Fall'}
years = 1997:2013;
for s = 1:length(Seasons)
    for y = 1:length(years)
        csvwrite(['r2_' Seasons{s} '_' num2str(years(y)) '.csv'], ['r2_' Seasons{s} '_' num2str(years(y))])
    end
end

Solution

  • If I understand what you are trying to do, I think you will need to use eval( ) to get the data into the csvwrite function. Something like this:

    csvwrite(['r2_' Seasons{s} '_' num2str(years(y)) '.csv'], eval(['r2_' Seasons{s} '_' num2str(years(y)))])