How to write multiple input into one csv file
64 次查看(过去 30 天)
显示 更早的评论
Let say I have
a=1;
b=2;
c=3;
d=4;
I want to put this output value in matlab to a csv file in the order below.
![ff.PNG](https://www.mathworks.com/matlabcentral/answers/uploaded_files/204704/ff.png)
I can use below, However, it will over-write the csv file.
>> csvwrite('1test.csv',a)
>> csvwrite('1test.csv',b, 0,1)
>> csvwrite('1test.csv',c, 0,2)
>> csvwrite('1test.csv',d, 0,3)
Thanks!
0 个评论
回答(2 个)
Arvind Sathyanarayanan
2019-2-18
dlmwrite(filename,M,'-append')
The other option is to store a,b,c,d in a array and then write that array to the csv file.
3 个评论
Walter Roberson
2019-2-18
No. dlmwrite() always ends the line with newline, and the -append always puts the new data after the end of the current file (and so after the newline.)
If you need to do what you are indicating, then you have several choices:
- Save all of the data into an array and csvwrite() it once at the end
- Save all of the data into an array and dlmwrite() it once at the end
- Use xlswrite(), as you can specify output location for it. You would need to keep track of where the current output location was.
- Use writetable() with 'writevariablenames' false. You would need ot keep track of where the current output location was.
- Use fopen() / fprintf() / fclose() with the exact format you want, instead of relying on the pre-built functions such as csvwrite() and dlmwrite()
- If you are using MS Windows with Excel installed, you can use ActiveX to talk to Excel and send it the data to be appened as you go. You would have to use Excel's functions to keep adjusting the current selection range so that you write into the correct place.
Mohammad Farhad Aryan
2020-3-12
Use the following code:
a = 1;
b = 2;
c = 3;
d = 4;
Nums = [a, b, c, d];
writematrix(Nums, 'Nums.csv')
2 个评论
Walter Roberson
2020-3-12
The original poster wanted to be able to write incrementally, doing separate write operations each of which appended a column of data. writematrix() can only do that for "spreadsheet" (.xls, .xlsx) files and not for "text" files (such as .csv), and writematrix() needs to be told exactly where to write the data each time.
The only system of calls that comes close to providing an "append into next column" operation is directly using ActiveX to talk to Excel, in which case certain kinds of range selections automatically update to position themselves after data that is written. Otherwise your choices are the ones I described at https://www.mathworks.com/matlabcentral/answers/445664-how-to-write-multiple-input-into-one-csv-file#comment_672637
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Spreadsheets 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!