2

I wish to write a some information in form of a csv file from a MATLAB code.

In the MATLAB code I have stored the header as a cell array:

ToCSV={'Location' 'Weight_factor' 'Average' 'Maximum' 'Minimum'};

I append rows to this cell array by looping. A sample statement is:

ToCSV={ToCSV; {'EastLocation' 0.5 1e+3 1e+4 1e+2} };

I wish to print this as a csv file. I used following routine which sort of giving errors:

fid = fopen('outfile.csv','w');
fprintf(fid,'%s, %s, %s, %s, %s\n',ToCSV{1,:});
fprintf(fid,'%s, %f, %10.2e, %10.2e, %f\n',ToCSV{2:end,:});
fclose(fid);

>>Error using fprintf
>>Function is not defined for 'cell' inputs.

Can some of you please provide pointers to achieve this? I also tried csvwrite, but apparently it doesn't go well with cell arrays.

3
  • what version are you running on? Commented Dec 5, 2013 at 3:56
  • @XiaoleiZhu, my MATLAB version is R2012a Commented Dec 5, 2013 at 4:02
  • I was gonna suggest using tables and writetable function, but I guess that might not be available in your version. Commented Dec 5, 2013 at 4:56

2 Answers 2

2

The problem is with the following statement

ToCSV={ToCSV; {'EastLocation' 0.5 1e+3 1e+4 1e+2} };

This makes a cell array inside a cell array so that when you index ToCSV you get a cell array. I think you want to concatenate a row like this:

ToCSV=[ToCSV; {'EastLocation', 0.5, 1e+3, 1e+4, 1e+2} ];

or

ToCSV(end+1,:) = {'EastLocation', 0.5, 1e+3, 1e+4, 1e+2};

The commas just make it easier to read.

Sign up to request clarification or add additional context in comments.

Comments

1
aa=ToCSV{1,:};
bb=ToCSV{2,:};
fid = fopen('outfile.csv','w');
fprintf(fid,'%s, %s, %s, %s, %s\n',aa{:});
fprintf(fid,'%s, %f, %10.2e, %10.2e, %f\n',bb{:});
fclose(fid);

2 Comments

He's looping. When the concatenation runs a second time, this breaks.
You are right. Thank you for pointing out. I +1 to your answer, that works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.