Adding a header to a matrix in Matlab

限于喜欢 提交于 2019-12-04 15:54:19

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...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!