pap-x
pap-x

Reputation: 594

Writing a matlab cell to a csv file

So I have a cell that has the following structure:

result{index} = {name, mean(winternights), max(winternights), var(winternights), sum(winternights)};

The name variable is a string but the rest are numbers. The only way I've found to write a cell to a csv file is the following:

fid = fopen('Measurements.csv','wt');
for i=1:size(result,1)
    fprintf(fid, '%s,%d,%d,%d,%d\n', result{i,:});
end
fclose(fid);

But this throws an error: ??? Error using ==> fprintf Function is not defined for 'cell' inputs.

What am I doing wrong?

Upvotes: 1

Views: 2692

Answers (2)

NKN
NKN

Reputation: 6424

Similar issue here.

You can do either this:

[nrows,ncols]= size(mycell);

filename = 'celldata.dat';
fid = fopen(filename, 'w');

for row=1:nrows
    fprintf(fid, '%s %d %d %d\n', mycell{row,:});
end

fclose(fid);

Or you can use this function cell2csv from Matlab central.

Upvotes: 0

Jonas
Jonas

Reputation: 74930

When you assign result, the call result{i} = {...} places a cell array inside the ith element of the cell array result. Thus, you need to change your file-writing code to the following

fid = fopen('Measurements.csv','wt');
for i=1:size(result,1)
    fprintf(fid, '%s,%d,%d,%d,%d\n', result{i}{:});
end
fclose(fid);

Upvotes: 1

Related Questions