Accessing data from a file and putting it into a matrix in Matlab, plus headers.
Show older comments
I am trying to read data in from a .svc file, which consists of 7 columns and 212 rows. I have managed to read it in by doing:
>>fid = fopen('u001_s01_sign_ds2-tb-0c_01.svc','r');
>>data = textscan(fid,'%f %f %f %f %f %f %f','HeaderLines',1);
>>fclose(fid);
I found it difficult to understand how to read data straight into a matrix, using dlmread, so have tried to go around using that, as above.
To store the data into a matrix after reading it in I used:
>>A=[data{1} data{2} data{3} data{4} data{5} data{6} data{7}]
Now I want to add headers to each column, but I am not sure how to go about that. I have found the following code, that looks like it will do what I need, but I do not understand it:
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);
This code was from http://stackoverflow.com/questions/7081721/adding-a-header-to-a-matrix-in-matlab . The comment to go with this was, ‘You just need to play with the fprintf format string...’. I have saved the code into a function in Matlab, saving it as writeWithHeader.m, and I understand that to run the function I type into the Matlab command window:
>> writeWithHeader('u001_s01_sign_ds2-tb-0c_01.svc', X Y Z A B C D, A)
Where X Y Z A B C D are my header names, and A is the matrix of data I want the headers added to. Is this correct? Is there maybe a better of doing all this?
Accepted Answer
More Answers (0)
Categories
Find more on Large Files and Big Data in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!