Skip to content Skip to sidebar Skip to footer

Read the Data of a Plot in Matlab

MATLAB(TM) Hypertext Reference,  	          Copyright (c) 1995 Gerald Recktenwald,  	          All rights reserved

Loading Data into MATLAB for Plotting

In addition to plotting values created with its own commands, MATLAB is very useful for plotting data from other sources, e.g., experimental measurements. Typically this data is available equally a plain text file organized into columns. MATLAB can easily handle tab or infinite-delimited text, merely it cannot straight import files stored in the native (binary) format of other applications such as spreadsheets.

The simplest way 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 become around this restriction you must employ 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 hardly a catholicon, this function is much more flexible than the load command because information technology allows you to provide documentation inside your data file.

Here's an outline of this section

  • The MATLAB load Command
  • A elementary plot of data from a file
  • Plotting information from files with column headings

The MATLAB load Command

There is more 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 unabridged contents of the file in a single step. The load command requires that the data in the file be organized into a rectangular assortment. No cavalcade titles are permitted. One useful form of the load command is

        load name.ext      

where ``proper name.ext'' is the name of the file containing the data. The outcome of this operation is that the data in ``name.ext'' is stored in the MATLAB matrix variable called proper name. The ``ext'' cord is whatsoever iii character extension, typically ``dat''. Whatsoever extension except ``mat'' indicates to MATLAB that the data is stored as patently ASCII text. A ``mat'' extension is reserved for MATLAB matrix files (see ``assistance load'' for more data).

Suppose you had a unproblematic ASCII file named my_xy.dat that contained two columns of numbers. The following MATLAB statements volition load this information 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);     %  copy first cavalcade of my_xy into x 	>> y = my_xy(:,2);     %  and 2nd cavalcade into y      

Y'all don't need to copy the information into x and y, of class. Whenever the ``ten'' data is needed you could refer to information technology as my_xy(:,1). Copying the data into ``ten'' and ``y'' makes the code easier to read, and is more aesthetically highly-seasoned. The duplication of the data will not tax MATLAB'south retention for well-nigh pocket-sized data sets.

The load control is demonstrated in the following example.

If the data 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 use the load command :-(
  • Use the fgetl control to read the heading information one line at at time. You can then parse the column labels with the strtok command. This technique requires MATLAB version iv.2c or later.
  • Use the fscanf command to read the heading information.

Of these options, using fgetl and strtok is probably the most robust and convenient. If you lot read the heading text into MATLAB, i.due east., if yous don't use the load command, then y'all will have to also read the plot information with fscanf. The example, Plotting data from files with column headings shows how this is done.



A simple plot of data from a file

This example show yous how to load a simple data fix and plot information technology.

The PDXprecip.dat file contains two columns of numbers. The starting time is the number of the month, and the second is the mean precipitation recorded at the Portland International Airport between 1961 and 1990. (For an abundance of weather data like this cheque 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.yard for yous to download.

        >> load PDXprecip.dat;         %  read data into PDXprecip matrix  	>> calendar month = PDXprecip(:,i);     %  copy get-go column of PDXprecip into month 	>> precip = PDXprecip(:,2);    %  and 2nd column into precip  	>> plot(month,precip,'o');     %  plot precip vs. month with circles  	>> xlabel('month of the yr');           % add together axis labels and plot championship 	>> ylabel('mean precipitation (inches)'); 	>> title('Mean monthly precipitation at Portland International Airport');      

Although the data in the calendar month vector is trivial, it is used here anyway for the purpose of exposition. The preceding statments create the post-obit plot.

Plot of y = sin(3*pi*x)


Plotting data from files with column headings

If all your data is stored in files that incorporate no text labels, the load command is all yous need. I like labels, however, because they allow me to certificate and forget nigh the contents of a file. To use the load for such a file I would have to delete the carefully written comments everytime I wanted to brand a plot. Then, in order to minimize my effort, I might stop adding the comments to the data file in the first identify. For united states command 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 information in the file PDXtemperature.dat is reproduced below

        Monthly averaged temperature (1961-1990) Portland International Airdrome 	Source:  Dr. George Taylor, 	Oregon Climate Service, http://www.ocs.oregonstate.edu/ 	 	Temperatures are in degrees Farenheit 	 	Calendar month   High     Low    Average 	1	45.36	33.84	39.half-dozen 	two	50.87	35.98	43.43 	3	56.05	38.55	47.3 	4	60.49	41.36	50.92 	5	67.17	46.92	57.05 	vi	73.82	52.eight	63.31 	7	79.72	56.43	68.07 	8	80.14	56.79	68.47 	nine	74.54	51.83	63.18 	x	64.08	44.95	54.52 	11	52.66	39.54	46.1 	12	45.59	34.75	40.17      

The file has a v line header (including blank lines) and each column of numbers has a text characterization. To use this data with the load command you would take to delete the text labels and salve the file. A meliorate solution is to have MATLAB read the file without destroying the labels. Amend all the same, nosotros should exist able to tell MATLAB to read and use the column headings when it creates the plot legend.

There is no congenital-in MATLAB command to read this information, so we take to write an m-file to exercise the job. One solution is the file readColData.m. The total text of that function won't be reproduced here. You can click on the link to examine the code and save it on your reckoner if you like.

Here is the prologue to readColData.one thousand

        role  [labels,ten,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  = proper 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 as well 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 	%                label from the columns of information.  The number of columns 	%                in the labels matrix equals the length of the longest 	%                column heading in the information file.  More than than one row of 	%                labels is allowed.  In this case the second row of column 	%                headings begins in row ncol+1 of labels.  The third row 	%                cavalcade headings begins in row 2*ncol+1 of labels, etc. 	% 	%          NOTE:  Individual column headings must not incorporate blanks 	% 	%     x = column vector of 10 values 	%     y = matrix of y values.  y has length(ten) rows and ncols columns      

The first line of the file is the function definition. Post-obit that are several lines of annotate statements that form a prologue to the function. Considering the first line after the part definition has a not-blank annotate statement, typing ``help readColData'' at the MATLAB prompt will crusade MATLAB to impress the prologue in the command window. This is how the on-line help to all MATLAB functions is provided.

The prologue is organized into four sections. Kickoff is a cursory statement of what the role does. Next is a synopsis of the means in which the function can be called. Post-obit that the input and output parameters are described.

Here are the MATLAB commands that utilize readColData.m to plot the data in PDXtemperature.dat. The commands are besides in the script file multicolPlot.g

        >>  %  read labels and x-y data 	>>  [labels,calendar month,t] = readColData('PDXtemperature.dat',4,5);  	>>  plot(calendar month,t(:,1),'ro',calendar month,t(:,2),'c+',calendar month,t(:,3),'grand-');  	>>  xlabel(labels(1,:));                      % add axis labels and plot championship 	>>  ylabel('temperature (degrees F)'); 	>>  championship('Monthly average temperature for Portland International Airport');  	>>  %  add together a plot legend using labels read from the file 	>>  legend(labels(2,:),labels(3,:),labels(4,:));      

These statments create the following plot.

Plot of High, Low and Average Temperatures



[Preceding Department] [Master Outline] [Section Outline] [Adjacent Department]

jonestepateady.blogspot.com

Source: https://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html

Enregistrer un commentaire for "Read the Data of a Plot in Matlab"