0

I would like to generate a csv file with a header and some data. Since I am on a Mac, this does not work using csvwrite, so I need to use fprintf.

I am storing my headers in a cell array called header (header = 'AB' 'CB'). Whatever I am trying I get an error:

Error using fprintf

Function is not defined for 'cell' inputs.

Can somebody make an easy example with the header example?

C.Colden
  • 627
  • 1
  • 8
  • 28

1 Answers1

0

Something like this should work,

headers ={'Header1','Header2','Header3'};
fh = fopen('SomeFile.csv','w');
for ii = 1:numel(headers)
   if ii == 1
      fprintf(fh,headers{ii});
   else
      fprintf(fh,[',',headers{ii}]); 
   end
end
randVals = rand(5,3);
for ii = 1:size(randVals,1)
       fprintf(fh,'\n');
    for jj = 1:size(randVals,2)
        if jj == 1
            fprintf(fh,num2str(randVals(ii,jj)));
        else
            fprintf(fh,[',',num2str(randVals(ii,jj))]);
        end
    end
end
fclose(fh)

You just need to separate out the headers and do the manual grunt work that csvwrite would normally do for you.

MZimmerman6
  • 8,445
  • 10
  • 40
  • 70