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

非 Y 不嫁゛ 提交于 2019-12-24 07:53:58

问题


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


回答1:


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)


来源:https://stackoverflow.com/questions/41978945/add-a-delimiter-to-end-of-each-line-of-csv-file-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!