write data in csv document with space delimiter
11 views (last 30 days)
Show older comments
Hi,
I have a series of data to be written in a csv file with space delimiter. I have it stored in my workspace as tables, vectors and double
The file I would like to create looks like this:
2
37
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7
11
0 2 3 4 5 6 5 4 2 3
0.1 3 4 5 6 7 8 4 3
0.2 3 4 5 6 7 5 3 3
0.3 3 4 5 2 3 4 5 6
37
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7
11
0 2 3 6 5 6 4 4 3 3
0.1 3 4 5 6 7 8 4 3
0.2 3 3 5 6 7 5 3 3
0.3 2 4 5 5 3 4 5 6
I have stored the data as
a=2;
b=37;
c=11;
d=[0 0.1 0.2 0.3 0.4 0.5 0.6 0.7];
e = [0 2 3 4 5 6 5 4 2 ,
0.1 3 4 5 6 7 8 4 3,
0.2 3 4 5 6 7 5 3 3,
0.3 3 4 5 2 3 4 5 6];
f = [0 2 3 6 5 6 4 4 3 ,
0.1 3 4 5 6 7 8 4 3,
0.2 3 3 5 6 7 5 3 3,
0.3 2 4 5 5 3 4 5 6];
e = table(e);
f= table(f);
So far I managed to store the tables concatenated in a csv file as
tt = [e
f];
writetable(tt,'myData.csv','Delimiter',' ')
I would like to store the rest of data as in the format shown above
Is there a way to use something like this for a csv file altering the range for each data to be stored?
writetable(tt,'myData.csv,'WriteVariableNames',false,'Sheet',1,'Range','A1')
thank you in advance
0 Comments
Answers (1)
AR
on 11 Feb 2025
Hi Ana!
CSV files do not support cell ranges like Excel, and as per the documentation for “writetable” function, the “Range” parameter is not applicable for CSV files. To control data placement, use MATLAB's “fprintf” function to manually write each data block in the desired order and format, ensuring correct placement in the file.
Check out the code below to store the data in the specified format.
% Open a file for writing
fileID = fopen('myData.csv', 'w');
% Write data to the file
fprintf(fileID, '%d\n', a);
fprintf(fileID, '%d\n', b);
fprintf(fileID, '%s\n', strjoin(arrayfun(@num2str, d, 'UniformOutput', false), ','));
fprintf(fileID, '%d\n', c);
for i = 1:size(e, 1)
fprintf(fileID, '%s\n', strjoin(arrayfun(@num2str, e(i,:), 'UniformOutput', false), ','));
end
fprintf(fileID, '%d\n', b);
fprintf(fileID, '%s\n', strjoin(arrayfun(@num2str, d, 'UniformOutput', false), ','));
fprintf(fileID, '%d\n', c);
for i = 1:size(f, 1)
fprintf(fileID, '%s\n', strjoin(arrayfun(@num2str, f(i,:), 'UniformOutput', false), ','));
end
% Close the file
fclose(fileID);
Some helpful reference links for the same:
Hope this helps!
0 Comments
See Also
Categories
Find more on Spreadsheets in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!