Part 2: Breaking Down the Code

The next piece of code deals with the header information.

for i=1:3
    readin = fgetl(id);
    para(i) = str2num(readin(6:length(readin)));
end
fgetl(id);

If all of your data files have the same number of rows in their header content, we can use a for loop to read it in. In this case, I have parameters n, d, and k that I need to read in. Thus, I want to run the for loop 3 times to read in 3 lines. Lets discuss what happens within this for loop. When i=1 (the first time through the loop), we have:

    readin = fgetl(id);

Once this line of code is executed, we get

readin= ‘n := 9′ , note that readin is of String type

We then move to the next line of code:

    para(i) = str2num(readin(6:length(readin)));

Once this line of code is executed, we get

para(i) = 9 , note that para(i) is of Number type

Anything you read in from the fgetl function will be a string value. But what we need in this case is the numerical value. One way to do this is to just grab the last few characters of the string in readin. In this case, the numerical value starts in the 6th character of the string (’n := ‘ accounts for the first 5). However, your parameter values could potentially have more than one digit. By reading in 6:length(readin) instead of 6 we ensure that all the digits for each parameter are read, making the code more flexible. Since the value obtained from fgetl function will be a string, we need to use the str2num function to convert from a String type into a Number type.

We are ready to read in the numerical data now! The line param p:1 2 3 4 5 := from the input file does not serve much purpose, so we can just call fgetl again to read it in, but not use it. This essentially creates a skipline in reading files. So now we just read in the numerical data with a simple for loop.

for i=1:para(1)
    data(i,:) = str2num(fgetl(id));
end

Recall that para(1) is where I stored the value n. So this for loop will run n times to read in all the data points I measured. This is convenient if your data sets have different number of data points. Just like before, I use the fgetl function to read in the data. But since all the values in the txt file are all numbers now, I can call the str2num function to convert the output of fgetl(id) into a numerical array. This data is stored in data(i,:).

fclose('all')

Lastly, use fclose to terminate Matlab’s read access to your file. If you don’t do this, Matlab will have the file ‘open’ and you won’t be able to open, move, or delete your file in your windows directory.

I hope this helps people reading in data into Matlab. I realize there can be several different formats in your file. But this is a basic foundation into reading more complicated format.

Pages: 1 2 3