简体   繁体   English

MATLAB一次导出多个.csv文件

[英]MATLAB export multiple .csv files at one time

I have a matrix where I need to export each column into a separate .csv file. 我有一个矩阵,需要在其中将每列导出到单独的.csv文件中。 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 . 因此,如果我想要第2列,则将变量更改为data (:,2)并将其保存为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. 如果将i放在引号之间,它将被视为字符而不是变量。 (In your case your filename will always be "(i).csv") (在您的情况下,您的文件名将始终为“(i).csv”)

You can concatenate strings using [ ], and since i is an integer you have to convert it to string using num2str() 您可以使用[]连接字符串,并且由于i是整数,因此必须使用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. PD:由于您将每一列(而不是每一行)存储在一个文件中,所以我不确定是否要在每个元素都位于单独行中的文件中,还是要将该列存储为一行并分开用逗号分隔。

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) 而不是复共轭' (这是常见的误用,因为只要使用实数,结果是相同的)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM