如何将结构数组的字段转换为.txt文件

时间:2016-05-03 06:49:05

标签: matlab

我有一个带有以下字段的结构数组model_dlib

model_dlib.refU
model_dlib.outA
model_dlib.ref_XY
model_dlib.render_width
model_dlib.render_height
model_dlib.sizeU
model_dlib.indbad
model_dlib.threedee 

我需要将model_dlib.refU字段(320×320×3 double)转换为.txt文件。我该怎么做?

我试过的东西(没用):

fid = fopen('C:\Users\cortana\Desktop\refU.txt', 'w');
fprintf (fid, '%s \f', model_dlib(1).refU{:,:,1});
fclose(fid);

1 个答案:

答案 0 :(得分:1)

这应该有效:

array_3d = model_dlib(1).refU;    %% A 320x320x3 matrix
array_2d = array_3d(:,:,1);       %% Extract the first layer
array_1d = array_2d(:).';         %% Make it a horizontal vector

%% Comma separated:
csvwrite('C:\Users\cortana\Desktop\refU.txt',array_1d)

这为您提供了一行逗号分隔文件:

0.56175,0.20139,0.25511,0.6222,0.37601,0.35895,0.028651,0.76737,0.23738,0.56175

如果你是一个单行爱好者(但请不要这样做,以后你会遇到一个大问题):

csvwrite('C:\Users\cortana\Desktop\refU.txt',reshape(model_dlib(1).refU(:,:,1),[],1))

更新了问题:

%% Space separated:
save('C:\Users\cortana\Desktop\refU.txt','array_1d','-ascii')

第一种方法给出:

0.56175,0.6222,0.028651
0.20139,0.37601,0.76737
0.25511,0.35895,0.2373

请注意,换行符中不会显示换行符。但是,如果您尝试在Notepad ++,MATLAB,MS Word,MS Excel ...中打开它,则会出现换行符。

第二种方法给出:

   5.6174979e-01   6.2220070e-01   2.8650626e-02
   2.0138985e-01   3.7601341e-01   7.6737463e-01
   2.5510711e-01   3.5895197e-01   2.3738395e-01