简体   繁体   English

MATLAB将两个数组(一个字符串单元格和一个数值向量)附加到一个.csv中

[英]MATLAB append two arrays(one string cell and one numeric vector) into a .csv

I have two arrays, X and Y 我有两个数组,X和Y

X has numeric data like this: X具有如下数字数据:

12342 1355 2324 ...

Y has strings like this: Y具有这样的字符串:

APPLE METRO BLANKET ...

I want to append these arrays into a pre-existing .csv in this format: 我想将这些数组以这种格式附加到预先存在的.csv中:

X(1,1), Y{1,1} X(2,1), Y{2,1} X(3,1), Y{2,1} ...

How should I do so? 我应该怎么做?

unfortunately writing cell arrays to csvs can be tricky. 不幸的是,将单元格数组写入csv可能很棘手。 One way or another you need to loop through so you can access the data within each cell. 您需要循环浏览一种或另一种方式,以便可以访问每个单元格中的数据。 The reason for cells not writing automatically is that a cell can contain anything - like a whole matrix of data. 单元不自动写入的原因是单元可以包含任何内容-就像整个数据矩阵一样。

The most versatile way that will allow for any types of cell/matrix combos is to use fprintf - you just need to specify a format. 允许任何类型的单元格/矩阵组合的最通用的方法是使用fprintf-您只需要指定一种格式即可。 http://au.mathworks.com/help/matlab/ref/fprintf.html http://au.mathworks.com/help/matlab/ref/fprintf.html

nrows = size(x,1);
fid = fopen('newfile.csv','w');
for aa = 1 : nrows
    fprintf(fid,'%f,%s\r\n', x(aa,1), y{aa,1});
end

you can use %d instead of %f if you are only chasing decimal numbers instead of floating point precision. 如果您只追求小数而不是浮点精度,则可以使用%d代替%f。

I have found fprintf to be faster than any of the alternatives for this sort of situation. 我发现fprintf比这种情况下的任何替代方法都快。 It is a little more low-level but allows you to write anything you like to file. 它稍微低一点,但是允许您编写任何您想归档的东西。

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

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