How to Use Fscanf to Read the Real Time Serial Data in Matlab
 
      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 space-delimited text, but it cannot directly import files stored in the native (binary) format of other applications such as spreadsheets.
        The simplest way to import your information into MATLAB is with the        load        command.  Unfortunately, the        load        control 	requires that your data file comprise no text headings or column 	labels.  To go around this restriction you must utilise more avant-garde 	file I/O commands.   Beneath I demonstrate both approaches with 	examples.  I've included an grand-file to handle the more circuitous case 	of a file with an capricious 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 considering 	it allows yous to provide documentation inside your information file.      
Hither's an outline of this section
-           The MATLAB          loadControl
- A simple plot of information from a file
- Plotting data from files with cavalcade headings
        The MATLAB        load        Command
              There is more one way to read data into MATLAB from a file.  	The simplest, though least flexible, process is to use the        load        control 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 array.  No column 	titles are permitted.  One useful form of the        load        command is      
load proper name.ext
        where ``name.ext'' is the name of the file containing the data. 	The result of this functioning is that the data in ``proper name.ext'' is 	stored in the MATLAB matrix variable called        name.  The 	``ext'' string is any three character extension, typically ``dat''.  	Any extension except ``mat'' indicates to MATLAB that the data 	is stored equally plain ASCII text.  A ``mat'' extension is reserved 	for MATLAB matrix files (encounter ``help load'' for more 	information).      
Suppose you had a simple ASCII file named my_xy.dat that contained ii columns of numbers. The post-obit MATLAB statements volition load this data into the matrix ``my_xy'', and so copy it into ii vectors, x and y.
>> load my_xy.dat; % read data into the my_xy matrix >> x = my_xy(:,1); % copy first column of my_xy into ten >> y = my_xy(:,two); % and 2nd cavalcade into y
You don't need to copy the information into x and y, of course. Whenever the ``x'' data is needed yous could refer to it as my_xy(:,ane). Copying the data into ``x'' and ``y'' makes the code easier to read, and is more aesthetically appealing. The duplication of the data volition not revenue enhancement MATLAB's retention for about modest data sets.
The load control is demonstrated in the following example.
If the data you wish to load into MATLAB has heading information, e.g., text labels for the columns, you have the post-obit options to deal with the heading text.
- Delete the heading information with a text editor and apply 	    the          loadcommand :-(
- Use the          fgetlcommand to read the heading information i line at at time. You can so parse the column labels with thestrtokcommand. This technique requires MATLAB version 4.2c or later on.
- Employ the          fscanfcontrol to read the heading data.
        Of these options, using        fgetl        and        strtok        is 	probably the virtually robust and convenient. If you read the heading 	text into MATLAB, i.e., if you lot don't use the        load        command, then you lot will have to also read the plot information with        fscanf.  The example, 	Plotting data from files with cavalcade headings 	shows how this is done.      
A uncomplicated plot of information from a file
This example bear witness you how to load a simple data gear up and plot information technology.
The PDXprecip.dat file contains two columns of numbers. The showtime is the number of the month, and the second is the hateful precipitation recorded at the Portland International Aerodrome between 1961 and 1990. (For an abundance of weather condition data like this cheque out the Oregon Climate Service)
Hither are the MATLAB commands to create a symbol plot with the data from PDXprecip.dat. These commands are too in the script file precipPlot.m for you lot to download.
        >> load PDXprecip.dat;         %  read data into PDXprecip matrix  	>> month = PDXprecip(:,1);     %  copy outset column of PDXprecip into calendar month 	>> precip = PDXprecip(:,2);    %  and second column into precip  	>> plot(month,precip,'o');     %  plot precip vs. month with circles  	>> xlabel('month of the yr');           % add centrality labels and plot title 	>> ylabel('mean precipitation (inches)'); 	>> title('Mean monthly precipitation at Portland International Airport');                    Although the data in the        month        vector is trivial, it 	is used here anyhow 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 incorporate no text labels, 	the        load        control is all y'all demand.  I similar labels, 	however, because they allow me to document and forget about 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 make a plot.  Then, in gild to minimize my endeavor, 	I might terminate adding the comments to the data file in the first place. 	For united states of america control freaks, that leads to an unacceptable increase 	in entropy of the universe!  The solution is to find a way 	to take MATLAB read and bargain with the text comments at the summit 	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 Calendar month High Low Average 1 45.36 33.84 39.6 two 50.87 35.98 43.43 3 56.05 38.55 47.3 four 60.49 41.36 50.92 5 67.17 46.92 57.05 six 73.82 52.eight 63.31 vii 79.72 56.43 68.07 8 80.fourteen 56.79 68.47 nine 74.54 51.83 63.18 ten 64.08 44.95 54.52 xi 52.66 39.54 46.one 12 45.59 34.75 40.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 amend solution is to have MATLAB read the 	file without destroying the labels.  Better all the same, we should be able 	to tell MATLAB to read and apply the cavalcade headings when information technology creates 	the plot fable.      
In that location is no built-in MATLAB control to read this data, so we have to write an g-file to exercise the job. One solution is the file readColData.m. The total text of that part won't exist reproduced here. You lot tin click on the link to examine the code and save it on your computer if yous like.
Here is the prologue to readColData.one thousand
function [labels,x,y] = readColData(fname,ncols,nhead,nlrows) % readColData reads information from a file containing data in columns % that take text titles, and possibly other header text % % Synopsis: % [labels,10,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 noun of the file containing the data (required) % ncols = number of columns in the information file. Default = 2. A value % of ncols is required only if nlrows is likewise specified. % nhead = number of lines of header information at the very peak 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 = 1 % % 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 % cavalcade heading in the information file. More one row of % labels is allowed. In this case the second row of column % headings begins in row ncol+1 of labels. The 3rd row % column headings begins in row ii*ncol+1 of labels, etc. % % NOTE: Individual column headings must not contain blanks % % ten = column vector of x values % y = matrix of y values. y has length(x) rows and ncols columns
The first line of the file is the role definition. Following that are several lines of comment statements that grade a prologue to the function. Because the offset line after the function definition has a non-blank comment statement, typing ``assistance 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 four sections. Outset is a brief statement of what the function does. Next is a synopsis of the means in which the role tin can be called. Following that the input and output parameters are described.
Hither are the MATLAB commands that employ readColData.m to plot the data in PDXtemperature.dat. The commands are besides in the script file multicolPlot.one thousand
        >>  %  read labels and ten-y data 	>>  [labels,month,t] = readColData('PDXtemperature.dat',4,5);  	>>  plot(month,t(:,1),'ro',month,t(:,two),'c+',month,t(:,3),'g-');  	>>  xlabel(labels(ane,:));                      % add together axis labels and plot championship 	>>  ylabel('temperature (degrees F)'); 	>>  title('Monthly average 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] [Main Outline] [Department Outline] [Adjacent Department]
schillingermoderfe1965.blogspot.com
Source: https://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html
0 Response to "How to Use Fscanf to Read the Real Time Serial Data in Matlab"
Post a Comment