Convert Matlab.mat to csv and save variable names

I am trying to convert a .mat file to csv while preserving vector / variable names. This is one example of what I mean:

mymat = model_id: [2217x1 double] own_dummies: [2217x26 double] id: [2217x1 double] product: [2217x1 double] const: [2217x1 double] mpd: [2217x1 double] air: [2217x1 double] mpg: [2217x1 double] trend: [2217x1 double] space: [2217x1 double] hpwt: [2217x1 double] cdindex: [20x1 double] cdid: [2217x1 double] outshr: [2217x1 double] firmid: [2217x1 double] share: [2217x1 double] price: [2217x1 double] 

I tried using csvwrite('test.csv', mymat) , but this gives me an error:

 ??? Undefined function or method 'real' for input arguments of type 'struct'. Error in ==> dlmwrite at 192 str = sprintf('%.*g%+.*gi',precn,real(m(i,j)),precn,imag(m(i,j)));\ Error in ==> csvwrite at 32 dlmwrite(filename, m, ',', r, c); 

I assume the problem is that I am feeding csvwrite a structure, not a matrix. I can convert a struct variable into a variable into a matrix, but then I would lose the variable names.

Of course, is there a better way?

+4
source share
1 answer

how would you actually render the structure in csv? you cannot make a direct map of field names as entries in the first row, because the matrices have incompatible sizes. So, in this example, you will need to: 1. enter some columns for own_dummies and 2. expand cdindex.

So, you can write a shell to make the matrices themselves compatible and write the columns to a file yourself. something along (untested, conceptual) lines

  function saveData(filename, data, type) % at first bring struct data to sensible format if strcmp(type)='my_mat_type' data.own_dummies2 = data.own_dummies[2,:]; % split into seperate columns %... data.own_dummies26 = data.own_dummies[26,:]; data.own_dummies = data.own_dummies[1,:]; data.cdindex = [data.cdindex -ones(1,2217-length(data.cdindex)]; % pad any missing values as -1 end; FD = fopen(filename, 'w'); %todo did it open? fields = fieldnames(data); nfields = length(fields); % create column name values columns = strcat(strcat(fields,',')); % creates string = col1,col2,...coln, columns = columns(1:length(columns)-1); %remove trailing comma CRNL = char([10 13]); % or so % print columns and newline fprintf(FD,strcat(columns,CRNL)); dataout = cell2mat(struct2cell(data)); % use your method to write the data to the file fclose(FD); 

Naturally, you can also simply separate the individual fields into separate files, where the field name is contained in the file name, which can be simpler, generally speaking.

+2
source

All Articles