How to write string in .CSV format?

115 views (last 30 days)
Rakesh Roshan
Rakesh Roshan on 30 May 2022
Commented: Walter Roberson on 31 May 2022
Name='data stored';
Input_data=[A B e Name]
I want to write string in dlmwrite format is it possible? 2018a version end
  1 Comment
Chris on 30 May 2022
Edited: Chris on 30 May 2022
You could use
but Input_data isn't going to be what you want, since you are trying to concatenate doubles with a char vector.
B=2; e=4; Name='data stored'; Input_data=[A B e Name]
Input_data = 'data stored'
more_correct = A + "," + B + "," + e + "," + Name
more_corect = "1,2,4,data stored"
number_strings = string([A;B;e]);
another_way = join([number_strings;Name], ",")
another_way = "1,2,4,data stored"

Sign in to comment.

Answers (1)

dpb on 30 May 2022
Name='data stored';
Input_data={A B e Name};
results in
>> type input.csv
1,2,4,"data stored"
Walter Roberson
Walter Roberson on 31 May 2022
Yes, it is possible with dlmwrite. What you need to do is convert everything you need to write into a cell array of character vectors, one per row, such as
Input_data{1} = sprintf( '%g,%g,%g,"%s"', A, B, e, Name);
Note that this required coding all of commas and double-quotes yourself.
dlmwrite(FILENAME, Input_data{1}, 'delimiter', '', 'precision', '%s') ;
Now loop over the remaining entries in the cell Input_data, doing a separate dlmwrite call for each one, like the above but adding also 'Writemode', 'append' to the list of options.
What this code would be doing is opening the output file for each row, writing out one row, closing the file, and then looping back for the next row. The array of data you would be passing to dlmwrite would be the individual character vector that was the already-formatted text for the line. Remember that a character vector is an array of characters, so as far as dlmwrite is concerned it would be writing out as many columns as there were characters in the vector. The 'Delimiter', '' would tell dlmwrite to skip the normal comma between columns, and the 'precision', '%s' tells it to write each entry in the vector as a character.
This is all very ugly and inefficient, and the only reason to do this is to prove that it can be done. If you were going to preformat the lines anyhow then a single fopen(), fprintf(), fclose() would be much more efficient. And if you use fopen(), loop the fprintf, then fclose() you can format as you go.

Sign in to comment.


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!