Lucas
Lucas

Reputation: 65

Add a delimiter to end of each line of csv file MATLAB

I am appending to a csv file. The current code outputs a line: a;b;c;d I need it to output a;b;c;d; notice the extra ';' at the end of d. That is essential

 matrix = [a,b,c,d]
 dlmwrite('matrix.csv', matrix, 'delimiter',';','-append','roffset',0, 'precision',14)

any help would be appreciated. I have had to keep variables a,b,c and d as numbers, or it makes it a character vector (or something) which makes my csv look funny

Upvotes: 1

Views: 665

Answers (1)

Max Chandler
Max Chandler

Reputation: 513

I've always had problems with the MatLab inbuild CSV writing methods. Why don't you code your own .CSV writing method?

Here, you could make a function something like:

function write_to_csv(filepath, matrix)
  csv = fopen(filepath, 'a+'); % check what sort of open you'd like : https://uk.mathworks.com/help/matlab/ref/fopen.html#inputarg_permission
  for ii = 1 : numel(matrix)   % this loop depends on the dimensions of your matrix
    fprintf(csv, '%s;', matrix(ii)); % check fprintf return type, depending on the data in the matrix : https://uk.mathworks.com/help/matlab/ref/fprintf.html?searchHighlight=fprintf&s_tid=doc_srchtitle#inputarg_formatSpec
  end 
  fclose(csv);
end

This works for a 1D matrix you've supplied, run with:

write_to_csv('matrix.csv',matrix)

Upvotes: 1

Related Questions