I have a matrix where I need to export each column into a separate .csv file. I know the number of columns and I can achieve my desired result if I specifically select one column to export. I would do this by:
dlmwrite('1.csv',data(:,1), 'precision', 9)
Therefore if I want column 2 I would change the variable to data (:,2)
and save this as 2.csv
.
So I want a loop that will do all this automatically. I have tried
for i=1:Number_of_Columns
dlmwrite('(i).csv',csv_data(:,(i)), 'precision', 9)
end
which clearly won't work but I am unsure how to do it.
Any help or advice would be much appreciated
Your problem is the filename. If you put i
between quotes it will be taken as character instead of a variable. (In your case your filename will always be "(i).csv")
You can concatenate strings using [ ], and since i is an integer you have to convert it to string using num2str()
Try:
for i=1:Number_of_Columns
dlmwrite([num2str(i) '.csv'], csv_data(:,i), 'precision', 9)
end
PD: Since you are storing each column (not each row) in a file, I'm not sure if you want a file where each element is in a separate line, or if you want the column to be stored as a row and separated by commas.
If you want the latter, transpose your column:
dlmwrite([num2str(i) '.csv'], csv_data(:,i).', 'precision', 9)
Note that the transpose operator is .'
instead of the complex conjugate '
(this is a common misuse since the results are the same as long as you only use real numbers)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.