Read First 5 Lines of Txt File Matlab
Loading Data into MATLAB for Plotting
In addition to plotting values created with its own commands, MATLAB is very useful for plotting information from other sources, eastward.k., experimental measurements. Typically this information is bachelor as a obviously text file organized into columns. MATLAB can easily handle tab or space-delimited text, but information technology cannot direct import files stored in the native (binary) format of other applications such as spreadsheets.
The simplest mode to import your data into MATLAB is with the load
command. Unfortunately, the load
command requires that your data file contain no text headings or column labels. To get around this restriction you lot must use more than advanced file I/O commands. Below I demonstrate both approaches with examples. I've included an m-file to handle the more complex case of a file with an arbitrary number of lines of text header, in addition to text labels for each column of data. Though inappreciably a cure-all, this function is much more than flexible than the load
command considering it allows yous to provide documentation inside your information file.
Hither'southward an outline of this section
- The MATLAB
load
Control - A unproblematic plot of data from a file
- Plotting data from files with column headings
The MATLAB load
Command
There is more than than one way to read data into MATLAB from a file. The simplest, though least flexible, process is to use the load
command to read the entire contents of the file in a single pace. The load
command requires that the data in the file exist organized into a rectangular array. No column titles are permitted. One useful class of the load
command is
load name.ext
where ``name.ext'' is the proper noun of the file containing the data. The result of this performance is that the information in ``name.ext'' is stored in the MATLAB matrix variable called name
. The ``ext'' string is whatsoever three character extension, typically ``dat''. Whatsoever extension except ``mat'' indicates to MATLAB that the information is stored every bit plain ASCII text. A ``mat'' extension is reserved for MATLAB matrix files (encounter ``assistance load'' for more information).
Suppose you had a elementary ASCII file named my_xy.dat that contained two columns of numbers. The post-obit MATLAB statements will load this data into the matrix ``my_xy'', and then copy it into two vectors, x and y.
>> load my_xy.dat; % read data into the my_xy matrix >> x = my_xy(:,1); % re-create outset cavalcade of my_xy into ten >> y = my_xy(:,ii); % and 2nd column into y
You don't need to copy the information into 10 and y, of course. Whenever the ``x'' data is needed y'all could refer to information technology equally my_xy(:,1). Copying the information into ``x'' and ``y'' makes the code easier to read, and is more aesthetically appealing. The duplication of the data will not revenue enhancement MATLAB's retentiveness for most modest data sets.
The load command is demonstrated in the following example.
If the information you wish to load into MATLAB has heading information, due east.g., text labels for the columns, you have the following options to deal with the heading text.
- Delete the heading information with a text editor and utilize the
load
control :-( - Utilize the
fgetl
command to read the heading information one line at at fourth dimension. You lot tin can then parse the column labels with thestrtok
command. This technique requires MATLAB version 4.2c or later. - Use the
fscanf
command to read the heading information.
Of these options, using fgetl
and strtok
is probably the near robust and convenient. If you lot read the heading text into MATLAB, i.e., if you lot don't use the load
command, so you will have to also read the plot data with fscanf
. The example, Plotting data from files with column headings shows how this is done.
A simple plot of information from a file
This case prove you how to load a unproblematic data set and plot it.
The PDXprecip.dat file contains 2 columns of numbers. The first is the number of the month, and the second is the mean precipitation recorded at the Portland International Drome betwixt 1961 and 1990. (For an affluence of weather information like this check out the Oregon Climate Service)
Here are the MATLAB commands to create a symbol plot with the data from PDXprecip.dat. These commands are as well in the script file precipPlot.m for you lot to download.
>> load PDXprecip.dat; % read data into PDXprecip matrix >> month = PDXprecip(:,1); % re-create first cavalcade of PDXprecip into month >> precip = PDXprecip(:,2); % and second column into precip >> plot(calendar month,precip,'o'); % plot precip vs. month with circles >> xlabel('calendar month of the year'); % add axis labels and plot title >> ylabel('mean precipitation (inches)'); >> championship('Hateful monthly atmospheric precipitation at Portland International Airport');
Although the information in the calendar month
vector is trivial, it is used hither anyway for the purpose of exposition. The preceding statments create the following plot.
Plotting data from files with column headings
If all your data is stored in files that contain no text labels, the load
command is all you need. I like labels, however, because they let me to document and forget almost the contents of a file. To use the load
for such a file I would accept to delete the carefully written comments everytime I wanted to brand a plot. Then, in gild to minimize my attempt, I might end adding the comments to the data file in the first place. For us control freaks, that leads to an unacceptable increase in entropy of the universe! The solution is to find a way to have MATLAB read and deal with the text comments at the top of the file.
The post-obit example presents a MATLAB function that can read columns of data from a file when the file has an arbitrary length text header and text headings for each columns.
The data in the file PDXtemperature.dat is reproduced below
Monthly averaged temperature (1961-1990) Portland International Airport Source: Dr. George Taylor, Oregon Climate Service, http://www.ocs.oregonstate.edu/ Temperatures are in degrees Farenheit Month Loftier Low Average i 45.36 33.84 39.vi 2 l.87 35.98 43.43 3 56.05 38.55 47.3 4 sixty.49 41.36 fifty.92 5 67.17 46.92 57.05 6 73.82 52.8 63.31 7 79.72 56.43 68.07 viii 80.14 56.79 68.47 nine 74.54 51.83 63.18 ten 64.08 44.95 54.52 11 52.66 39.54 46.1 12 45.59 34.75 twoscore.17
The file has a five line header (including blank lines) and each column of numbers has a text label. To use this data with the load
command you would have to delete the text labels and save the file. A better solution is to have MATLAB read the file without destroying the labels. Better yet, nosotros should be able to tell MATLAB to read and use the cavalcade headings when it creates the plot legend.
There is no built-in MATLAB command to read this data, and then nosotros take to write an grand-file to do the task. I solution is the file readColData.yard. The total text of that office won't be reproduced here. You tin can click on the link to examine the code and save information technology on your reckoner if you like.
Here is the prologue to readColData.m
function [labels,x,y] = readColData(fname,ncols,nhead,nlrows) % readColData reads data from a file containing data in columns % that have text titles, and possibly other header text % % Synopsis: % [labels,x,y] = readColData(fname) % [labels,x,y] = readColData(fname,ncols) % [labels,x,y] = readColData(fname,ncols,nhead) % [labels,x,y] = readColData(fname,ncols,nhead,nlrows) % % Input: % fname = name of the file containing the data (required) % ncols = number of columns in the data file. Default = 2. A value % of ncols is required only if nlrows is also specified. % nhead = number of lines of header data at the very meridian of % the file. Header text is read and discarded. Default = 0. % A value of nhead is required only if nlrows is also specified. % nlrows = number of rows of labels. Default = i % % Output: % labels = matrix of labels. Each row of lables is a different % characterization from the columns of information. The number of columns % in the labels matrix equals the length of the longest % cavalcade heading in the information file. More than one row of % labels is immune. In this case the second row of column % headings begins in row ncol+i of labels. The 3rd row % cavalcade headings begins in row two*ncol+one of labels, etc. % % NOTE: Individual column headings must not incorporate blanks % % 10 = column vector of x values % y = matrix of y values. y has length(x) rows and ncols columns
The kickoff line of the file is the function definition. Following that are several lines of comment statements that grade a prologue to the function. Because the first line later the office definition has a non-blank comment statement, typing ``help readColData'' at the MATLAB prompt will cause MATLAB to print the prologue in the control window. This is how the on-line aid to all MATLAB functions is provided.
The prologue is organized into iv sections. First is a brief statement of what the office does. Next is a synopsis of the ways in which the function can be chosen. Following that the input and output parameters are described.
Here are the MATLAB commands that apply readColData.grand to plot the data in PDXtemperature.dat. The commands are also in the script file multicolPlot.m
>> % read labels and x-y information >> [labels,month,t] = readColData('PDXtemperature.dat',iv,5); >> plot(calendar month,t(:,1),'ro',month,t(:,2),'c+',month,t(:,3),'k-'); >> xlabel(labels(1,:)); % add axis labels and plot title >> ylabel('temperature (degrees F)'); >> title('Monthly boilerplate temperature for Portland International Airport'); >> % add a plot legend using labels read from the file >> legend(labels(2,:),labels(3,:),labels(4,:));
These statments create the following plot.
[Preceding Section] [Master Outline] [Section Outline] [Next Section]
Source: https://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html
0 Response to "Read First 5 Lines of Txt File Matlab"
Post a Comment