Search code examples
matlabappendexport-to-csv

Appending new rows at the end of an existing CSV file


I have a MATLABcode it produces multi-output as a array and all of them have 20 rows and 1 column, for every iteration I have same result that is 5 array: Input, Ftn_Noise_real, Ftn_Noise_imag, After_Matchfilter_real, After_Matchfilter_imag (all of them have 20 rows and 1 column). Then I merge this five array as one array (20 rows and 5 columns) in the code block. I try to write this array in a csv file by the help of csvwrite. But in every iteration, it overwrite the new data on results of previous iteration.

I want to merge output of all iterations. For example first iteration code writes a array which is combination of these five array like shown image of data, then second iteration it should be start to write from 20th rows to 40th, and so on. In the end I got to have a csv file which contains 80 rows and 5 columns.

for EbNo = 0:2:4
%here some codes block produce array
.
.
.
%Writing part
filename = ['DATA' '.csv'];
%here ı merge all array as an one array. Then with csvwrite ı transfer these in a csv
newdata = [Input,Ftn_Noise_real,Ftn_Noise_imag,After_Matchfilter_real,After_Matchfilter_imag];
csvwrite(filename,newdata);
end

My data like this


Solution

  • If you are using R2019a or newer, you can use writematrix. It also supports appending to an existing file:

    filename = 'test.csv';
    if (exist(filename, 'file'))
        delete(filename);
    end
    for i=1:4
        A = randi(3, 4);
        writematrix(A, filename, 'WriteMode', 'append');
    end
    readlines('test.csv')
    

    But a better way would be merging all matrices into one matrix, and then write the whole data by calling csvwrite or writematrix only once:

    r = 3; % No. of rows
    c = 4; % No. of columns
    n_iter = 4; % No. of iterations
    B = zeros(r*n_iter, c); % pre-allocating B matrix
    for ii=1:n_iter
        A = randi(10, r, c);
        B(((ii-1)*r)+(1:r), :) = A; % appending A to the end of B
    end
    writematrix(B, filename);
    readlines('test.csv') % test contents