如何从矩阵创建文件.txt?

时间:2016-06-19 10:16:40

标签: matlab matrix

我有一个矩阵x_training(大小:1000 * 2304)和另一个矩阵y_training(大小1000 * 1),其中包含x_training中每个实例的标签。我的目标是创建一个包含标签和x_training的文件.txt。这是一个简化的小例子:

x_training=[0.2 0.3
         0.5 0.4
         0.5 0.9]
y_training=[1
           2
           3]

因此,file.txt将包含:

   1  0.2 0.3
   2  0.5 0.4
   3  0.5 0.9

我该怎么做?

4 个答案:

答案 0 :(得分:3)

简单。在MATLAB Current文件夹中创建一个文件(比如说OutPutFile.txt)并运行这个脚本:

A = [y_training x_training];
B = A';

fileID = fopen('OutPutFile.txt','w');
fprintf(fileID, '%i %2.1f %2.1f \n',B);
fclose(fileID);

如果要创建制表符分隔值(TSV)文件(可在Excel中打开),请将第2行修改为:

fprintf(fileID, '%i \t %2.1f \t %2.1f \n', B);

答案 1 :(得分:3)

x_training=[0.2 0.3; 0.5 0.4; 0.5 0.9]; % X
y_training=([1 2 3])';                  % Y - transposed       

data = [y_training,x_training];         % x and y concatenated
data = table(data);                     % data converted to table
writetable(data, 'file.txt');           % data saved as file.txt 

答案 2 :(得分:1)

最终编辑

你可以创建一个矩阵数据,其中第一列是y_training而2:end,列是x_training?

如果不能正常工作,请试着告诉我

data=[y_training x_training(:,1:2304)] %based on your matrix
fId = fopen( 'your file.txt', 'w' ) ;
 fprintf( fId, '%i %2.1f %2.1f \r\n', data(:) ) ; % update this line
 fclose( fId ) ;

由于我没有你的矩阵,为什么这里有测试这个代码的演示

    x_training=rand(1000,2304); % creating randomly 1000*2304 matrix as x_training
y_training=rand(1000,1); % creating randomly 1000*1 matrix as y_training
test=[y_training x_training(:,1:end)];
data=test;
fId = fopen( 'your file.txt', 'w' ) ;
 fprintf( fId, '%i %2.1f %2.1f \r\n', data(:) ) ;
 fclose( fId ) ;

替代方法

如果上面的代码没有给出欲望输出,请更新此

data=[y_training x_training(:,1:2304)] %based on your matrix
dlmwrite('myFile.txt', data);

检查并告诉我哪一个是好的代码。

答案 3 :(得分:1)

这是另一种方法

dlmwrite('testtext2.txt',['x_training  y_training'] ,'delimiter','') 
A(:,1) = y_training
A(:,2:3) = x_training
dlmwrite('testtext2.txt',[A],'-append','delimiter','\t','roffset',1)