1
votes

I have googled many times to solve my peculiar situation about writing/output to file without much success.

I have a for loop which generates me 1 cell matrix and 1 regular matrix. For each loop the Cell Matrix can be of variable length. Assuming dimentions of <1x5>, the cell matrix stores the following strings:

Aggregated Day, AggreVal from Curve, Val3_Name, Val4_Name, Val5_Name

The cell matrix can have different content and size for next loop.

The numeric matrix is of same size as cell matrix and represents the values corresponding to names in cell matrix. Hence, for this loop it has size 1x5 and stores values as:

1.3, 1300, 14, 15, 16

I want to write the above cell and numeric matrix to ONE single file (preferrably excel or txt file for future manipulation) as they are being generated. First I want to output the cell matrix and right after that numeric matrix. Followed by cell matrix of second loop and so on.

I remember it being very easy to do so in C++ by opening the file in append mode, but it appears to be tricky here in Matlab. I have tried playing with xlswrite, dlmwrite, xlsappend, etc but nothing has worked so far.

Hence, the output file will look something like:

Loop1
Aggregated Day, AggreVal from Curve, Val3_Name, Val4_Name, Val5_Name
1.3, 1300, 14, 15, 16

Loop2
Aggaed Dy, AgeVal fm Curve, China, Val4_Name, Brazil
1.453, 1300, 1774, 1115, 1613

Thanks

3

3 Answers

1
votes

Could you avoid closing the file until after all the loops have finished, i.e.:

fid = fopen('filename.txt','w');

% Loop stuff, adding lines to your file

fclose(fid);

It looks like the kind of output you want is a custom format, rather than an xls file, which assumes a table-like structure. Try using fprintf to print your data:

foo = {'abc','def','ghi'};
foo2 = [1 2 3 4];
fid = fopen('foo.txt','w');
fprintf(fid, '%s ', foo{:});
fprintf(fid, '\n');
fprintf(fid, '%f ', foo2);
fprintf(fid, '\n');
fclose(fid)
0
votes

I'd do this:

A{1} = {'Aggregated Day', 'AggreVal from Curve', 'Val3_Name', 'Val4_Name', 'Val5_Name'}
A{2} = {1.3, 1300, 14, 15, 16};
B = cat(1,A{:});
xlswrite(filename,B);
0
votes
%s={'Aggregated Day', 'AggreVal from Curve', 'Val3_Name', ...
   'Val4_Name', 'Val5_Name'};

%n=[1.3, 1300, 14, 15, 16];

filename='myfile.xlsx'; % Change it to myfile.txt if needed for text version

% the trick is to retain the row number to append contents

%N = no. of entries.
for k = 1:2:N                %Sheet        %Row
    xlswrite( filename, s ,    1,    sprintf('A%d',k)   )
    xlswrite( filename, n ,    1,    sprintf('A%d',k+1) )
end