Technical Solutions
How do I make the names in my file header the names of the variables I load?
Date Last Modified: Friday, June 26, 2009
| Solution ID: |
|
1-17YYD |
| Product: |
|
MATLAB |
| Reported in Release: |
|
R11.1 |
| Platform: |
|
All Platforms |
| Operating System: |
|
All OS |
Subject:
How do I make the names in my file header the names of the variables I load?
Problem Description:
I have column headers at the top of my file and I want to name my variables in MATLAB the same names.
Solution:
Assume that a file named 'WCorrVols45obs.txt' stores tab delimited data whose column wise contents you would like to assign to the variables with the names same as the column headers in the file.:
Step 1: Read the column headers in the file and store them in a variable along with the tab spaces.
%open file fid = fopen('WCorrVols45obs.txt','r'); %discard first row of headers fgetl(fid); %retrieve column headers headers = fgetl(fid); %close file fclose(fid);
Step 2: Convert the column headers into individual elements stored in a cell array. You can call this function (which will parse a tab separated file):
function names = getvarnames(tempstr) %Given a string containing variable names separated by spaces %this function returns a cell array containing each variable name. % %Written by Megean McDuffy 06/21/00
index = 0; while length(tempstr > 0) index = index + 1; %the fliplr function flips the array left to right this line of %code will take blanks off of the front and back of the header name tempstr = fliplr(deblank(fliplr(deblank(tempstr))));
%if its the last variable name %char(9) represents a tab if isempty(find(tempstr == char(9))) names{index} = tempstr; tempstr = []; else %grab the name names{index} = tempstr(1:find(tempstr == char(9))-1); tempstr(1:find(tempstr == char(9))) = []; end end
Step 3: Use EVAL statements to copy the column data into the individual elements of the cell array created above.
headercell = getvarnames(headers);
and then, read in your data and assign the names to your data:
%call textread to retrieve the data from your file [a,b,c,d,e,f,g] = textread('WCorrVols45obs.txt','%d %s %f %f %f %f %f','headerlines',2); %make the names of your variables the names in the header cell array eval([headercell{2},' = b']) eval([headercell{3},' = c']) eval([headercell{4},' = d']) eval([headercell{5},' = e']) eval([headercell{6},' = f']) eval([headercell{7},' = g'])
|
|
|
|