开发者

Adding a header to a matrix in Matlab

I hope you guys are having a nice Tuesday so far. I realize that you cannot add a string header to a numerical matrix in MATLAB. I am trying to add headers to a matrix I currently have and output it to a tab-delimited text file. From my research, I know that the matrix has to be converted into a cell, but I am having trouble saving the cell using dlmwrite.

Here is the matrix I currently have:

  0         0         0
0.0454    0.0105    0.0105
0.0907    0.0066    0.0068
0.1814    0.0038    0.0049
0.3629    0.0034    0.0040
0.7258    0.0029    0.0023
1.4515    0.0002    0.0007
2.9030    0.0003    0.0005

This is what I want:

 tau     TOL Adev  FOL Adev
0.0454    0.0105    0.0105
0.0907    0.0066    0.0068
0.1814    0.0038    0.0049
0.3629    0.0034    0.0040
0.7258    0.0029    0.0023
1.4515    0.0002    0.0007
2.9030 开发者_C百科   0.0003    0.0005

The matrix(3, 7 with zeros in the first row) is called saveData.

I have tried assigning header = ['tau', 'TOL Adev', 'FOL Adev']; and output = {header;saveData}; but I cannot figure out how to use dlmwrite('filename', output, '\t').

Thank you so much for the help! -Alex


If you are feeling lazy and your matrix is not too big, you can make your data into a dataset, then export it. If your matrix is large, I recommend you look at the link Amro has given. Note dataset is a function in the Statistics Toolbox.

ds = dataset({rand(10,3) 'a' 'b' 'c'})
export(ds, 'file', 'foo.txt', 'delim', '\t');


First of all, this code (header = ['tau', 'TOL Adev', 'FOL Adev'];) will concatenate your strings, so use cells.

@Amro code is good, but if you want to make the output pretty (like in the example), you need to do yourself, like this function:

function writeWithHeader(fname,header,data)
% Write data with headers
%
% fname: filename
% header: cell of row titles
% data: matrix of data

f = fopen(fname,'w');

%Write the header:
fprintf(f,'%-10s\t',header{1:end-1});
fprintf(f,'%-10s\n',header{end});

%Write the data:
for m = 1:size(data,1)
    fprintf(f,'%-10.4f\t',data(m,1:end-1));
    fprintf(f,'%-10.4f\n',data(m,end));
end

fclose(f);

You just need to play with the fprintf format string...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜