Is there an example of how to save column-separated data under the column header name in MATLAB?

1 view (last 30 days)
If my data looks like:
H1 H2 H3 H4
0 1.0 5 6
1 2.3 7 8
2 3.2 9 1
3 4.7 2 3
I want the data to be saved in MATLAB as:
whos
Name Size Elements Bytes Density Complex
H1 4 by 1 4 32 Full No
H2 4 by 1 4 32 Full No
H3 4 by 1 4 32 Full No
H4 4 by 1 4 32 Full No
Grand total is 16 elements using 128 bytes
H1
H1 =
0
1
2
3
H2
H2 =
1.0000
2.3000
3.2000
4.7000
H3
H3 =
5
7
9
2
H4
H4 =
6
8
1
3

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 23 Apr 2010
You can use IMPORTDATA to import data like this. For help with IMPORTDATA, type the following at the MATLAB command prompt:
help importdata
You could also use the following example:
Here is an example of how to read a data file with columns into MATLAB variable names. The variable names in MATLAB match the column headers of the data file.
Save this as test.dat:
H1 H2 H3 H4
0 1.0 5 6
1 2.3 7 8
2 3.2 9 1
3 4.7 2 3
Save this as test.m:
% get a file handle
fid=fopen('test.dat','r');
% read in the first line
line = fgetl(fid);
% parse the line for variable names
if(~isempty(line))
zz = 1;
line_size = size(line,2);
tmpstring = [];
varlist = [];
while(zz <= line_size)
% assume the variable names are separated by spaces
if (real(line(zz)) ~= 32)
tmpstring = [tmpstring line(zz) ];
zz = zz+1;
else
if(~isempty(varlist))
varlist = str2mat(varlist,tmpstring);
else
varlist = str2mat(tmpstring);
end
tmpstring = [];
% increment the list until the next non-space
while(zz < line_size & real(line(zz)) == 32 )
zz = zz+1;
end
end
end
if(~isempty(tmpstring))
varlist = str2mat(varlist,tmpstring);
end
end
tmpmatrix = fscanf(fid,'%f %f %f %f',[4,inf])';
fclose(fid);
% assign the variable names
for(zz = 1:size(varlist,1))
eval( [ varlist(zz,:) ' = tmpmatrix(:, ' num2str(zz) ');'])
end
clear ans fid line line_size tmpmatrix tmpstring varlist zz

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!