Salut Macro
Embed Size (px)
Transcript of Salut Macro
-
8/8/2019 Salut Macro
1/41
Salut macro,
voici les codes pour ouvrir un file et ecrire le resultat d'une operation
Tu trouveras 2 attach files
un est un file matlab
et l'autre est un txt
ils font la meme chose, au cas ou tu ne pourrai pas ouvrire le matlabfile, copy le contenu du file
macro.txt et colle le dans un file matlab
Execute le en appuyant sur F5
Normalement il doit te demander
1-d'entrer le premier nombre, tu entre un nombre et tu appuis sur le bouton entree
2- la meme chose pour le 2nd nombre, apres avoir appuye sur entree
va dans le repertoire matlab il doit etre dans mes documents,
ouvre le fichier try01, tu verras le resultat de l'operation
Fait moi signe si PB
Dvid
% This program open a file name try01 if the file does not exist it would crfeate it.
% the file will be in the matlab file ( path :my document\matlab)% we define two variable var1 and var2 that the user should input from the matlab command line
% the summation of these variable is inputing to the variable "result"% We write the contain of result inside the file try01
fid = fopen('try01.txt','at'); %we open the file try01 or create it if it does not exist
var1=input('Give the first number'); %ask the user to input a numbervar2=input('Give the first number'); %idem
result=var1+var2; %computing the result
fprintf(fid,'the resultat is %d\n',result); %write the result into the file try01, and go to theline(\n)
fclose(fid); %terminate the program by closing the file
% This program open a file name try01 if the file does not exist it would crfeate it.
% the file will be in the matlab file ( path :my document\matlab)
-
8/8/2019 Salut Macro
2/41
% we define two variable var1 and var2 that the user should input from the matlab command line
% the summation of these variable is inputing to the variable "result"
% We write the contain of result inside the file try01
fid = fopen('try01.txt','at'); %we open the file try01 or create it if it does not exist
var1=input('Give the first number'); %ask the user to input a number
var2=input('Give the first number'); %idem
result=var1+var2; %computing the result
fprintf(fid,'the resultat is %d\n',result); %write the result into the file try01, and go to the
line(\n)
fclose(fid); %terminate the program by closing the file
Loading Data into MATLAB for Plotting
In addition to plotting values created with its own commands, MATLAB is very useful forplotting data from other sources, e.g., experimental measurements. Typically this data is
available as 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 otherapplications 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 get
around this restriction you must use more 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 cure-all, this function is much more flexible than the load command
because it allows you to provide documentation inside your data file.
-
8/8/2019 Salut Macro
3/41
Here's an outline of this section
The MATLAB load Command
A simple plot of data from a file
Plotting data 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, procedure is to use the load command to read the entire 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 name.ext
where ``name.ext'' is the name of the file containing the data. The result of this operation is thatthe data in ``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 as plain ASCII text. A ``mat'' extension is reserved forMATLAB matrix files (see ``help load'' for more information).
Suppose you had a simple ASCII file named my_xy.dat that contained two columns of numbers.
The following 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); % copy first column of my_xy into x>> y = my_xy(:,2); % and second column into y
You don't need to copy the data into x and y, of course. Whenever the ``x'' data is needed you
could refer to it as my_xy(:,1). Copying the data into ``x'' and ``y'' makes the code easier to read,and is more aesthetically appealing. The duplication of the data will not tax MATLAB's memory
for most modest data sets.
The load command is demonstrated in the following example.
If the data you wish to load into MATLAB has heading information, e.g., text labels for thecolumns, you have the following options to deal with the heading text.
Delete the heading information with a text editor and use the load command :-(
http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html#loadCommandhttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html#loadCommandhttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html#loadCommandhttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html#loadCommandhttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html#loadCommandhttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html#loadAndPlothttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html#colHeadingshttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html#loadAndPlothttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html#loadAndPlothttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html#colHeadingshttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html#loadAndPlothttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html#loadCommand -
8/8/2019 Salut Macro
4/41
Use the fgetl command 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 4.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
read the heading text into MATLAB, i.e., if you don't use the load command, then 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 data from a file
This example show you how to load a simple data set and plot it.
The PDXprecip.datfile contains two columns of numbers. The first 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 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 also in the script fileprecipPlot.m for you to download.
>> load PDXprecip.dat; % read data into PDXprecip matrix>> month = PDXprecip(:,1); % copy first column of PDXprecip into
month >> precip = PDXprecip(:,2); % and second column into precip
>> plot(month,precip,'o'); % plot precip vs. month with circles
>> xlabel('month of the year'); % add axis labels and plottitle
>> 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 anyway for the purpose of
exposition. The preceding statments create the following plot.
http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html#colHeadingshttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html#colHeadingshttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/examples/PDXprecip.dathttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/examples/PDXprecip.dathttp://www.ocs.oregonstate.edu/http://www.ocs.oregonstate.edu/http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/examples/precipPlot.mhttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html#colHeadingshttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html#colHeadingshttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/examples/PDXprecip.dathttp://www.ocs.oregonstate.edu/http://www.ocs.oregonstate.edu/http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/examples/precipPlot.m -
8/8/2019 Salut Macro
5/41
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 allow me to document and forget about 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 make a plot. Then, in order to minimize my effort, I might stop 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 following 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 InternationalAirport
Source: Dr. George Taylor,Oregon Climate Service, http://www.ocs.oregonstate.edu/
Temperatures are in degrees Farenheit
Month High Low Average1 45.36 33.84 39.62 50.87 35.98 43.433 56.05 38.55 47.34 60.49 41.36 50.925 67.17 46.92 57.056 73.82 52.8 63.317 79.72 56.43 68.07
http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/examples/PDXtemperature.dathttp://www.ocs.oregonstate.edu/http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/examples/PDXtemperature.dathttp://www.ocs.oregonstate.edu/ -
8/8/2019 Salut Macro
6/41
8 80.14 56.79 68.479 74.54 51.83 63.1810 64.08 44.95 54.5211 52.66 39.54 46.112 45.59 34.75 40.17
The file has a five line header (including blank lines) and each column of numbers has a textlabel. 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, we should be able to tell MATLAB to read and use the column headings when it creates the
plot legend.
There is no built-in MATLAB command to read this data, so we have to write an m-file to do thejob. One solution is the file readColData.m. The full text of that function won't be reproduced
here. You can click on the link to examine the code and save it on your computer 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 information at the very top
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 data. The number of
columns% in the labels matrix equals the length of the longest% column heading in the data file. More 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% column headings begins in row 2*ncol+1 of labels,
etc.
http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/examples/readColData.mhttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/examples/readColData.m -
8/8/2019 Salut Macro
7/41
%% NOTE: Individual column headings must not contain blanks%% x = 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 function definition. Following that are several lines of commentstatements that form a prologue to the function. Because the first line after the function definitionhas a non-blank comment statement, typing ``help readColData'' at the MATLAB prompt will
cause MATLAB to print 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. First is a brief statement of what the function does.Next is a synopsis of the ways in which the function can be called. Following that the input and
output parameters are described.
Here are the MATLAB commands that use readColData.m to plot the data in
PDXtemperature.dat. The commands are also in the script file multicolPlot.m
>> % read labels and x-y data>> [labels,month,t] = readColData('PDXtemperature.dat',4,5);
>> plot(month,t(:,1),'ro',month,t(:,2),'c+',month,t(:,3),'g-');
>> xlabel(labels(1,:)); % add axis labels andplot title
>> 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.
http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/examples/multicolPlot.mhttp://web.cecs.pdx.edu/~gerry/MATLAB/plotting/examples/multicolPlot.m -
8/8/2019 Salut Macro
8/41
Lecture 6: Manipulating Text
Objectives
By the end of the session you should:
be able to write simple functions and programs that manipulate text files and
tables of strings.
be able to re-use a number of simple programming templates for some common
programming tasks.
Outline
1. Writing to a text file
-
8/8/2019 Salut Macro
9/41
To save the results of some computation to a file in text format reqires the following
steps:
a. Open a new file, or overwrite an old file, keeping a handle for the file.
b. Print the values of expressions to the file, using the file handle
c. Close the file, using the file handle
The file handle is a just a variable which identifies the open file in your program.
This allows you to have any number of files open at any one time.
% open filefid = fopen('myfile.txt','wt'); % 'wt' means "write text"if (fid < 0)
error('could not open file "myfile.txt"');end;
% write some stuff to filefor i=1:100
fprintf(fid,'Number = %3d Square = %6d\n',i,i*i);end;% close the filefclose(fid);
2. Reading from a text file
To read some results from a text file is straightforward if you just want to load the
whole file into memory. This requires the following steps:
a. Open an existing file, keeping a handle for the file.
b. Read expressions from the file into a single array, using the file handle
c. Close the file, using the file handle
The fscanf() function is the inverse of fprintf(). However it returns the values it
reads as values in a matrix. You can control the 'shape' of the output matrix with a
third argument.
A = fscanf(fid,"%g %g %g\n",[3,inf]) % A has 3 rows and 1 col per linedisp(A(1,1)) % display first value on first linedisp(A(1,2)) % display first value on second linedisp(A(2,1)) % display second value on first line
Thus to read back the data we saved above:
-
8/8/2019 Salut Macro
10/41
% open filefid = fopen('myfile.txt','rt'); % 'rt' means "read text"if (fid < 0)
error('could not open file "myfile.txt"');end;
% read from file into table with 2 rows and 1 column per linetab = fscanf(fid,'Number = %d Square = %d\n',[2,inf]);% close the filefclose(fid);rtab = tab'; % convert to 2 columns and 1 row per line
Reading a table of strings is more complex, since the strings have to be the same
length. We can use the fgetl() function to get a line of text as characters, but we'll
first need to find out the length of the longest string, then ensure all strings are the
same length. Here is a complete function for loading a text file as a table of fixed-
length strings:
function tab=readtextfile(filename)% Read a text file into a matrix with one row per input line% and with a fixed number of columns, set by the longest line.% Each string is padded with NUL (ASCII 0) characters%% open the file for readingip = fopen(filename,'rt'); % 'rt' means read textif (ip < 0)
error('could not open file'); % just abort if errorend;% find length of longest linemax=0; % record length of longest string
cnt=0; % record number of stringss = fgetl(ip); % get a linewhile (ischar(s)) % while not end of file
cnt = cnt+1;if (length(s) > max) % keep record of longest
max = length(s);end;s = fgetl(ip); % get next line
end;% rewind the file to the beginningfrewind(ip);% create an empty matrix of appropriate sizetab=char(zeros(cnt,max)); % fill with ASCII zeros% load the strings for realcnt=0;
s = fgetl(ip);while (ischar(s))
cnt = cnt+1;tab(cnt,1:length(s)) = s; % slot into tables = fgetl(ip);
end;% close the file and returnfclose(ip);return;
-
8/8/2019 Salut Macro
11/41
Here is an example of its use:
% write some variable length strings to a fileop = fopen('weekdays.txt','wt');fprintf(op,'Sunday\nMonday\nTuesday\nWednesday\n');fprintf(op,'Thursday\nFriday\nSaturday\n');fclose(op);% read it into memorytab = readtextfile('weekdays.txt');% display itdisp(tab);
3. Randomising and sorting a list
Assuming we have a table of values, how can we randomise the order of the
entries? A good way of achieving this is analogous to shuffling a pack of cards. Wepick two positions in the pack, then swap over the cards at those two positions. We
then just repeat this process enough times that each card is likely to be swapped at
least once.
function rtab=randomise(tab)% randomise the order of the rows in tab.% columns are unaffected[nrows,ncols]=size(tab); % get size of input matrixcnt = 10*nrows; % enough timeswhile (cnt > 0)
pos1 = 1+fix(nrows*rand); % get first random rowpos2 = 1+fix(nrows*rand); % get second random rowtmp = tab(pos1,:); % save first rowtab(pos1,:) = tab(pos2,:); % swap second into firsttab(pos2,:) = tmp; % move first into secondcnt=cnt-1;
end;rtab=tab; % return randomised tablereturn;
Sorting a list is easy if you just want some standard alphabetic ordering. But what if
you want to choose some arbitrary ordering function? For example, how could you
sort strings when case was not important? Here we use the ability of MATLAB toevaluate a function by name (feval()) so that we can provide the name of a function
for doing the comparisons the way we want. This function should take two rows and
return 1 if the first row sorts earlier than the second, 1 if the second row sorts
earlier than the first and 0 if there is no preference. Here is a case-independent
comparison function:
-
8/8/2019 Salut Macro
12/41
function flag=comparenocase(str1,str2)% compares two strings without regard to case% returns 1, 0, 1 if str1 is less than, equal, greater than str2.len1=length(str1);len2=length(str2);for i=1:min(len1,len2)
c1 = str1(i);
c2 = str2(i);if (('a'
-
8/8/2019 Salut Macro
13/41
How might we search a list of items for an item matching a specific value? If the list
is unordered, all we can do is run down the list testing each entry in turn. This
function finds the index of a row in a table that contains (anywhere) the characters
in the supplied match string:
function idx=findstring(tab,str)% find the row index containing a matching string% returns 0 if the string is not found[nrows,ncols]=size(tab);for idx=1:nrows
matches = findstr(tab(idx,:),str);if (length(matches)>0)
return;end;
end;idx=0;return;
However, the process can be much faster if the listed is sorted and we are
searching for an exact match only. A so-called binary search is the fastest possible
way of finding an item in a sorted list:
function idx=binarysearch(tab,val)% returns the row index of val in sorted table tab% returns 0 if val is not found[nrows,ncols]=size(tab);lo=1;hi=nrows;
while (lo tab(idx,:))
lo = idx + 1;else
return;end;
end;idx=0;return;
5. Cell Arrays
Many operations with text and tables of strings are made simpler in MATLAB
through the use of "cell arrays". These are a generalisation of MATLAB matrices
such that cells can contain any type of object. This allows MATLAB to manipulate
tables of variable length strings. We will not be going into cell arrays in this course.
-
8/8/2019 Salut Macro
14/41
Reading
MATLAB Online Manual: Using MATLAB: Index of Examples
Exercises
For these exercises, use the editor window to enter your code, and save your
answers to files under your account on the central server. When you save the files,
give them the file extension of ".m". Run your programs from the command
window. You may want to start by implementing the readtextfile() function from this
handout.
1. Write a program (ex61.m) to ask the user to input the name of a text file
containing a list of WAV format sound files. Play these sounds out in random
order.
2. Write a program (ex62.m) to ask the user to input the name of a text file
containing a list of general knowledge TRUE/FALSE questions. Prompt the user
with each question in turn and save his/her responses to an output file.
3. Write a program (ex63.m) to input a word list from a file and then to spell check
another text file. Treat as mis-spelled all words not in the word list, and report a
list of all mis-spelled words, ensuring that each mis-spelling is reported once
only.
4. (Homework) Write a program that takes the name of a text file containg a list of
WAV format sound files. Concatenate the audio files into a single WAV file with 3
seconds of silence between them. Be sure to check that sampling rates are
compatible.
Ex 6
% ex61.m% ask for file containing list of sound fileslname = input('Enter sound list file name : ','s');% read list into memorytab = readtextfile(lname);% randomise listrtab = randomise(tab);% play out the files
http://www.phon.ucl.ac.uk/courses/spsci/matlab/ex61.m.txthttp://www.phon.ucl.ac.uk/courses/spsci/matlab/ex62.m.txthttp://www.phon.ucl.ac.uk/courses/spsci/matlab/ex63.m.txthttp://www.phon.ucl.ac.uk/courses/spsci/matlab/ex61.m.txthttp://www.phon.ucl.ac.uk/courses/spsci/matlab/ex62.m.txthttp://www.phon.ucl.ac.uk/courses/spsci/matlab/ex63.m.txt -
8/8/2019 Salut Macro
15/41
[nrows,ncols]=size(rtab);for i=1:nrows
[y,fs,nbits] = wavread(rtab(i,:));wavplay(y,fs); % wavplay waits for sound to end
% unlike the SOUND functionend;
% ex62.m% ask for question file nameqname = input('Enter file containing questions : ','s');
% create a log file based on that namelname = [ qname '.log' ];% open the input fileip = fopen(qname,'rt');if (ip < 0)
error('could not open input file');end;% open the output fileop = fopen(lname,'wt');if (op < 0)
error('could not open output file');end;% ask each question in turn
q = fgetl(ip);while (ischar(q))
fprintf('%s\n',q);a = input('Answer T(rue) or F(alse) : ','s');while ((a~='T')&(a~='F'))
a = input('Answer T(rue) or F(alse) : ','s');end;fprintf(op,'%s\nAnswer: %s\n',q,a);q = fgetl(ip);
end;fclose(ip);fclose(op);
% ex63.m% get word list filewname = input('Enter word list file name : ','s');% load file and sortwtab = readtextfile(wname);swtab = sortrows(wtab);[nrows,ncols]=size(swtab);
-
8/8/2019 Salut Macro
16/41
fprintf('%d words loaded from "%s"\n',nrows,wname);% open a temporary output fileop=fopen('temp.txt','wt');if (op < 0)
error('could not open "temp.txt"');end;% get the text file nametname = input('Enter text file name : ','s');ip=fopen(tname,'rt');if (ip < 0)
error('could not open input file');end;% load the input file as a single columntxt=fscanf(ip,'%c');fclose(ip);% convert all characters except alphabetic letters to spacesnonalphas= ~((('A'
-
8/8/2019 Salut Macro
17/41
'Sally'types =
'Level1'x =12.34000000000000
y =45
answer ='Yes'
by Kristian Sandberg
Department of Applied Mathematics
University of Colorado
This worksheet introduces the fundamental ideas for programming in Matlab. It requires noprogramming experience, but some familiarity with Matlab is recomended. All background
needed can be found on the worksheet Introduction to Matlab.
The programming structures presented below applies to Matlab. However, these structures look
very similar in other computer languages, such as C, Java, Pascal, etc., so by understanding howloops, logical operations, etc., work in Matlab, you will be well-prepared for beginning
programming in other languages as well.
Many of the examples given may seem to be irrelevant to this course. However, by
understanding the seemingly stupid and sometimes mathematically irrelevant examples and
exercises in this worksheet, you will have all the background to write programs such as a Runge-Kutta 4 ODE-solver.
A number of examples will be given below. They will be given as Matlab code but the output
which you will get when you run these programs will not be given. When going over thisworksheet, you are recomended to implement the examples yourself and then run them in the
Matlab command window and carefully study the outcome and compare it to the code.
How to edit and run a program in Matlab
When writing programs, you need to do this in a separate window, called the editor.
On a Mac or PC you open this document form the "File" menu by choosing either
"New...M-file" (if you want to create a new program) or "Open" (to open an old
document). In the editor you can now type in your code, similarily to how you would
type using a word processor. There are menus for editing the text, just as in a word
processor. While typing your code in the editor, no commands will be performed! In
order to run a program do the following:
http://amath.colorado.edu/courses/2460/0LDER/1999Sum/Worksheets/ws2.htmlhttp://amath.colorado.edu/courses/2460/0LDER/1999Sum/Worksheets/ws2.html -
8/8/2019 Salut Macro
18/41
1. Save your code as filename.m. Important: It is important to add ".m" at theend of your filename. Otherwise Matlab may not understand your program.
2. Go to the command window. If necessary, change directory with the cdcommand to the directory contatining your file. For example, if you savedyour file on the C-drive, type cd c:.
3. In order to run the program, type filename at the prompt. Important:When typing filename in the command window in order to run a program, donot include ".m". When pressing enterMatlab will run your program andperform all the commands given in your file.
In case your code has errors, Matlab will complain when you try to run the program in the
command window. When this happens, try to interpret the error message and make necessary
changes to you code in the editor. After you have made the changes, make sure you save yourfile before trying to run the program again in the command window.
General programming advice
When programming, it is extremely important, even for the most experienced
programmer, to never try to write all the code at once. You have to program in
small steps and make sure each of these small steps work as expected before
proceeding to program the next step. When writing longer code, always use pen
and paper to outline the code before you actually type it into the editor.
Basic programming structures
Input/Output
To make Matlab give an output, such as return the value of a variable, you type the
name of the variable without any semi colon (;) following the variable. In many
cases, there is no need to see the value of a variable every single time Matlab uses
it. If Matlab re-computes the value of a variable 1000 times, we probably don't want
to see the result every single time. To surpress the output of a value, just add a
semi colon after the variable. Then Matlab will perform the command, but will not
show it on the screen.
Let's say that we want the user to enter some value that we want the program to work with. Thiscan be done using the inputcommand with the syntax
variable=input('text');
This command will print out texton the screen and then wait for the user to enter a number. The
variable will now be assigned the number that the user entered. (Using this command for reading
-
8/8/2019 Salut Macro
19/41
letters instead of numbers is slightly more complicated and will not be covered in this
worksheet.)
Now it is time for our first example. The following program asks the user for an amount indollars, and returns the value of this amount in a foreign currency.
Example 1.
clear
exchange_rate = 0.5;
amount = input('Give amount in dollars: ');
amount_in_foreign_currency = exchange_rate*amount
Always begin your code with clear! This erases all variables. If you do not do this, you canget errors when you run your program that are very hard to discover.
Relational and logical operators
The heading may sound scary but are just fancy names for some of the
fundamental operators used for programming. Below follows a list with some useful
commands.
Logical
operators
Operation:Matlab
command:
Logical and &
Logical or |
Negate ~
Relational operators
Operation:Matlab
command:
Strictly less than
-
8/8/2019 Salut Macro
20/41
Less than or equal
to
Greater than orequal to
>=
Equal to ==
Not equal to ~=
It is important to know the difference between = and ==. The former, =, is used when assigninga number to a variable, e.g., x=3;. The latter, ==, is used to check if two expressions are equal.
This is illustrated in the examples below, but first we need to know what an if-statement is.
When programming we often want the computer to check whether a statement is true or false andperform different operations depending on the result of this test. This can be done using a so-
called if-statement. The syntax is given below.
iflogical expression
commands
else
commands
end
Note that for each if, you need to "close" the if-statement with an end. Make sure the if:s
and end:s always match! (This is a common source for programming errors.)
The content of this paragraph may have seemed abstract but by carefully studying the following
three examples and doing Exercise 1 it will hopefully become clearer.
Example 2.
clear
N = input('Give numerator: ');
D = input('Give denominator: ');
-
8/8/2019 Salut Macro
21/41
if D==0
'Sorry, cannot divide by zero'
else
ratio = N/D
end
In the next example, I make Matlab write something depending on which test our month
"passes". To make Matlab write text as output, use single quote ' around the text.
Example 3.
clear
month = input('Give month number (1-12): ' );
if month==1 | month==3 | month ==5 | month==7 | month==10 |
month==12
'Your month has 31 days'
else
if month==2
'Your month has 28 days'
else
'Your month has 30 days'
end
end
In the next example I use the command rem (remainder). The syntax is
rem(x,y)
and returns the remainder after the division of the two integers x and y.
Example 4.
-
8/8/2019 Salut Macro
22/41
clear
number = input('Give an integer: ' );
remainder2 = rem(number,2);
remainder3 = rem(number,3);
if remainder2==0 & remainder3==0
'Your number is divisible by both 2 and 3'
else
if remainder2==0
'Your number is divisble by 2 but not by 3'
else
if remainder3==0
'Your number is divisible by 3 but not by 2'
else
'Your number is not divisible by either 2 or 3'
end
end
end
Exercise 1.
Write a "currency exchange program" similar to the one in Example 1 which can
handle two different exchange rates, exchange_rate1 = 0.5 and exchange_rate2 =
0.25. Design the program to first ask for the amount in dollars and then ask the user
which rate (represented by the numbers 1 and 2 respectively) he/she wants. Let the
program return the amount in the requested foreign currency.
Repetitive operations (loops)
The power of computers is that they can do operations repeatedly. For example, an
ODE-solvers computes the value of a function several thousands of times when
choosing a small time step. An operation that is performed repeatedly is called a
-
8/8/2019 Salut Macro
23/41
repetitive operation or, more common, a loop. There are different kinds of loops but
the most common one is the for-loop. The syntax for a for-loop is:
forloop variable = startvalue :
endvalue
commands
end
This loop will initate loop variable asstart value, increment loop variable by 1 each step untilend value is reached. Below follows a few examples of how to use for-loops.
Example 5.
clear
for i=1:20
x(i)=i/7;
end
x
In the following example we see a so-called nested for-loop. This is nothing else then a "loop
within a loop". Note how we must "close" each for with and end. Make sure you understand
how this example works!
Example 6.
clear
for i=1:5
for j=1:5
A(i,j)=10*i+j;
end
end
-
8/8/2019 Salut Macro
24/41
A
In the following example, make sure you understand the function of the variable sum. This is a
common way of performing summations when programming.
Example 7.
clear
sum = 0;
for k=0:10
sum = sum+1/gamma(k+1);
end
e_approximation = sum
e_exact = exp(1)
In the next example, notice how I have to "shift" the indexing of the vector. Matlab must have
non-zero, positive integers as vector- or matrix-indices! One of the most common mistakes whenprogramming in Matlab is that your program begins indexing at zero instead of one. Also note
how by typing a percent sign (%) before text in the code, Matlab does not interpret this text as
code. It just serves as a comment for any person using the code. Commenting your code is
essential when writing longer programs.
Example 8.
clear
for k=0:50
x(k+1)=0.1*k; % Indices of vectors must be NON-ZERO!
sum = 0;
for m=0:10
sum = sum+(x(k+1)^m)/gamma(m+1);
end
e(k+1) = sum;
-
8/8/2019 Salut Macro
25/41
end
plot(x,e)
title('Approximation of e^x for x between 0 and 5')
xlabel('x')
ylabel('e^x')
Exercise 2.
Write a program that approximates PI by computing the sum
.
The more terms you keep in the summation, the more accurate your answer will be.
(In fact, the series converges to PI as m goes to infinity.) See how many terms you
need to approximate PI with 5 decimals. (Note: This is by no means the most efficient
way to approximate PI, but the formula is quite beautiful...)
Exercise 3.
Use the sum given in Exercise 2 to approximate PI using 10, 100, 1000, 10000 and
100000 terms. For each of these number, compute the error of the approximation.
Plot the error as a function of the number of terms used in the sum.
Networks I
Course No. 0909-201-01
Fall 1997, 2nd Quarter
Introduction to Matlab
What is Matlab?
Matlab (short for MATrix LABoratory) is a language for technical computing,
developed by theThe Mathworks, Inc. It provides a single platform for
computation, visualization, programming and software development. All
problems and solutions in Matlab are expressed in notation used in linear
http://www.mathworks.com/http://www.mathworks.com/ -
8/8/2019 Salut Macro
26/41
algebra and essentially involve operations using matrices and vectors.
As part of the undergraduate Electrical Engineering program, you will be
using Matlab to solve problems in
o Circuits
o Communication systemso Digital signal processingo Control systemso Probability and statistics
In addition, you can use Matlab to build Graphical User Interfaces (GUIs) so
that you can develop user-friendly custom software.
The Matlab software environment has a core module (called Matlab) and
associated with that are a set of "Toolboxes" that perform specialized
computations.
MATLAB IS EASY!!!!!
A Matlab Tutorial
The following sections provide a brief introduction to some basic concepts
for programming in Matlab Version 5, that is installed in the laboratory. There
already exist many excellent tutorials developed by many universities for
their coursework. For a partial list of Matlab tutorials out on the web, click
here.
It is a good idea to purchase a Student Edition of Matlab from thebookstore, since you will be using this software throughout your engineering
career. It costs about $60 (need to check on the exact price) and comes with
a handy User's Guide.
The tutorial is organized into the following sections; just follow the links.
The best way to learn Matlab is by actually doing the examples indicated.
o Getting Startedo Vectors and Matriceso Vector and Matrix Operationso Loops
o Plottingo Printingo File Input/Outputo Executable files (m-files) in Matlab
http://users.rowan.edu/~shreek/networks1/matlablinks.htmlhttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Startedhttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Vectorshttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Operationshttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Loopshttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Plottinghttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Printinghttp://users.rowan.edu/~shreek/networks1/matlabintro.html#File%20Input/Outputhttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Executablehttp://users.rowan.edu/~shreek/networks1/matlablinks.htmlhttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Startedhttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Vectorshttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Operationshttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Loopshttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Plottinghttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Printinghttp://users.rowan.edu/~shreek/networks1/matlabintro.html#File%20Input/Outputhttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Executable -
8/8/2019 Salut Macro
27/41
Getting Started
Note: In all of the discussion in the following sections, stuff that you type in
will be written in boldface. All Matlab output will be normal font.
Double click on the Matlab icon to start the program (duh....). A MATLAB CommandWindow should pop-up with the following text:
To get started, type one of these commands: helpwin, helpdesk, or demo.
>>
The ">>" is a prompt, requiring you to type in commands. One of the first commands you shouldtype in is to find out what your working directory is. The working directory is where you will
save the results of your calculations. So, type in
>> pwd
pwd stands for "print working directory". You probably would get an output like:
ans =
\\ENGNET\MATLAB\bin
Matlab always stores the result of its last calculation in a variable called ans (short for answer).
Now this indicates the working directory. You can change the working directory using the cd
(short for change directory) command. Do>> cd C:\temp
>> pwd
ans =
C:\temp
Now, the results of your computations will be saved in the C:\temp directory, when you issue the
correct commands (more about that later).
Online help can be accessed for all Matlab commands by issuing the help command.
>> help
To get started, you can simply type
>> help
(Back to top)
http://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Top -
8/8/2019 Salut Macro
28/41
Vectors and Matrices
Variables in Matlab are just like variables in any other programming language (C,
C++ etc.); only difference is that you do not have to define them by indicating the
type etc. Also, variable names (case sensitive) can be used to refer to a single
number (a scalar), a set of numbers (a vector) or an array of numbers (a matrix).
Vectors are nothing but matrices having a single row (a row vector), or a single
column (a column vector).
To create a row vector in Matlab, do:
>> r = [1 2 3 4]
r =1 2 3 4
A column vector can be created by
>> c = [1; 2; 3; 4]c =
12
3
4On the other hand, you can use the ' operator (transpose)
>> c = r'
c =
12
3
4
Vectors can also be created by incrementing a starting value with a constant quantity. Forexample,
>> r = [0:2:10]
r =
0 2 4 6 8 10
creates a row vector, with the first element = 0; each element inceremented by 2; until the finalvalue of 10.
You can index specific parts of a vector. For example, to get the third element in the vector r,
you can do>> r(3)
ans =
-
8/8/2019 Salut Macro
29/41
4
Matrices are 2 dimensional quantities and are created similar to vectors. We can do
>> a = [1 2 3; 4 5 6; 7 8 9; 10 11 12] a =
1 2 3
4 5 6
7 8 910 11 12
which is a 4x3 matrix (4 rows and 3 columns). We can also use the incremenation principle to do
>> b = [0:2:10; 1:2:11]b =
0 2 4 6 8 10
1 3 5 7 9 11which is a 2x6 matrix. Again, individual elements of the matrix, for instance the element in the
2nd row, 5th column can be accessed using the notation:
>> b(2, 5)
ans =
9
(Back to top)
Vector and Matrix OperationsThe basic arithmetic operations +, -, *, / can be used for vectors and matrices.
These would generate corresponding output vectors or matrices. For example, to
add two vectors:
>> a = [1 2 3 4];
>> b = [5 6 7 8];
>> c = a+b
c =
6 8 19 12
The semicolons (;) in the first two commands direct Matlab not to echo the values of thevariables a and b on to the screen immediately after you type them. Obviously, only vectors that
have the same number of elements can be added or subtracted. Similarly, two matrices with
identical number of rows and columns can be subtracted as follows:
>> a = [1:3:20; 21:3:40];>> b = [2:3:20; 22:3:40];
>> c = a-b
c =
http://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Top -
8/8/2019 Salut Macro
30/41
-1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1
Matrix multiplication using the * symbol is possible only if the number of columns in the firstmatrix equals the number of rows in the second:
>> a=[1 2 3; 4 5 6]a =
1 2 34 5 6
>> b = a'
b =
1 4
2 5
3 6
>> c=a*b
c =
14 32
32 77
However, if you want to multiply corresponding elements of two matrices, then you do an array
multiply using the .* symbol.
>> a = [1 2 3 4; 5 6 7 8]; b=[2 2 2 2; 3 3 3 3]; >> c=a .* bc =
2 4 6 8
15 18 21 24
Discussion on matrix "division" using the / symbol for matrices is postponed till later.
Solving systems of linear equations in Matlab
To solve the set of equationsa1 x + b1 y + c1 z = d1
a2 x + b2 y + c2 z = d2a3 x + b3 y + c3 z = d3
we set this up as a matrix equation of the form
P U = Q
where
-
8/8/2019 Salut Macro
31/41
P = [a1 b1 c1; a2 b2 c2; a3 b3 c3]
U = [x; y; z]
Q = [d1; d2; d3]
The solution of this system of equations is U = P-1 Q; this is accomplished in Matlab using
>> U = inv(P)*Q
or by using the backslash \ operator
>> U = P\Q
Exercise:
1. Set up Mesh Current Equations in the form R I = V and solve for the meshcurrents, I.
2. Set up Node Voltage Equations in the form G V = I and solve for nodevoltages, V.
(Back to top)
Loops
The for loop (very similar to C expression) is a simple command for setting up a
loop. Example:
>> for i = 1:10;
>> a(i) = i*i;
>> end
>> aa =
1 4 9 16 25 36 49 64 81 100
All statements between the for and the end statements will be executed as per the command
specifications. Example of a for loop where the increment is not 1 would be >> for i =
1:3:20; ..... etc.
Type in
>> help forfor more details.
(Back to top)
Plotting
The plot command is used for generating 1-D (functions of one variable) plots. Do
>> help plot for complete details. Let's make a graph of y = sin(x), for x on the
http://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Top -
8/8/2019 Salut Macro
32/41
interval x=0, to x = 10.
>> x = [0:0.1:10];(here .1 is the increment)
>> y = sin(x);(notice how the sin function operates on each element of the entire
row vector x, to generate a nother row vector y)
>> plot (x, y)
Surface or 2-D (functions of two variables) plots are generated using the surfcommand. More
on that later.
To clear a plot, type in >> clg(clear graph)
To generate another plot window, do >> figure
(Back to top)
PrintingYou can print a plot using the Print Option under the File Menu in the Figure
Window. The text in the Command Window is printed similarly.
(Back to top)
File Input/Output
The save and load commands are used for saving data to disk or loading data from
disk, respectively.
To save values in a matrix or vector, called, for instance, y, do:
>> y = [1 2 3 4; 5 6 7 8];
>> save y.txt y -ascii
The -ascii option ensures that the data is saved in ASCII form, so that it can be read
by other programs - Word, Excel Notepad, Wordpad, etc. Examine the file y.txt
using one of these programs. The file is generated in the working directory
(remember this? If not click here).
An ASCII data file dat.txt can be loaded using
>> load dat.txt
This provides a variable called dat in the Matlab workspace. All manner of vector/matrix
operations can be performed on dat, just like any other variable.
Do >> help save and >>help load for learning all the load/save options.
After you read the next section, clickherefor a fun Matlab project - generating music with
Matlab!
http://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Startedhttp://users.rowan.edu/~shreek/networks1/music.htmlhttp://users.rowan.edu/~shreek/networks1/music.htmlhttp://users.rowan.edu/~shreek/networks1/music.htmlhttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Startedhttp://users.rowan.edu/~shreek/networks1/music.html -
8/8/2019 Salut Macro
33/41
(Back to top)
Executable files (m-files in Matlab)
Executable files in Matlab are generated by storing a list of Matlab commands in a
file given the extension .m
These files are called M-files. To create an M-file, use the New...M-file Option under
the File Menu in the Command Window. Type in the following commands in the M-
File Editor Window:
x = [0:0.1:10];
y = cos(x);
plot(x,y)
xlabel('x')
ylabel('y')
title('A plot of Cosine(x)')
Save the file using the Save Option under the File Menu in the M-File Editor Window. Call it,say, cosineplot.m. Now, to run this program in Matlab, move over to the Matlab Command
Window and just type in >> cosineplot
(Back to top)
Matlab Solenoid Example Program
Cut and paste this example program in to a blank m-file in Matlab, then saveit on your engin website with the name of your group and instrument(remember, Matlab allows only alphanumeric characters and no spacesbefore the ".m"). Modify the program (including the commented uppersection) to fit with your hardware.
% program solenoid.m% opens the COM1 serial port and sends a series of commands to a stepper% motor at location S2 on a Pontech S200B controller board
% written 27 October 2005 by E. Carr Everbachclear % clear all previous variablesncount = 1;ser = serial('COM1'); % establish connection between Matlab and COM1set(ser, 'Terminator', 'CR'); % set communication string to end on ASCII 13set(ser, 'BaudRate', 9600);set(ser, 'StopBits', 1); % Pontech controllers ask for these parametersset(ser, 'DataBits', 8);set(ser, 'Parity', 'none');fopen(ser); % open the serial port connection
http://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Tophttp://users.rowan.edu/~shreek/networks1/matlabintro.html#Top -
8/8/2019 Salut Macro
34/41
fprintf(ser,'BD0\n'); % address the controller board (assume only one of them)fprintf('servo controller is on-line.\n');nsolenoids = input('Enter number of solenoids to test: ');for index = 1:nsolenoids
fprintf(ser,'SV%d M0\n', index); % write out initialization commandsendwhile (ncount)
ncount = input('Enter number of in/out pulses to each solenoid (0 toquit): ');
for index = 1:ncountfor yndex = 1:nsolenoids % for each solenoid
fprintf(ser,'PS%d\n', yndex);pause(0.2);fprintf(ser,'PC%d\n', yndex);pause(0.5)
endend
enddisp('End of program');fclose(ser);
Matlab Servo Example Program
Cut and paste this example program in to a blank m-file in Matlab, then saveit on your engin website with the name of your group and instrument(remember, Matlab allows only alphanumeric characters and no spacesbefore the ".m"). Modify the program (including the commented uppersection) to fit with your hardware.
% program servo.m% opens the COM1 serial port and sends a series of commands to a servo
% motor at location S1 on a Pontech S200B controller board% written 3 October 2005 by E. Carr Everbachclear % clear all previous variablesser = serial('COM1'); % establish connection between Matlab and COM1set(ser, 'Terminator', 'CR'); % set communication string to end on ASCII 13set(ser, 'BaudRate', 9600);set(ser, 'StopBits', 1); % Pontech controllers ask for these parametersset(ser, 'DataBits', 8);set(ser, 'Parity', 'none');fopen(ser); % open the serial port connectionfprintf(ser,'BD0 SV1\n'); % write out initialization commandsfprintf('servo controller is on-line.\n');fprintf('Hit space to see servo toggle through its range\n');
pausefprintf('M255\n');fprintf(ser,'M255\n');pause(1)fprintf('M1\n');fprintf(ser,'M1\n');pause(1)position = 1; % variable to hold angular position infowhile (position)
position = input('Enter integer position (1-255) or 0 to quit: ');
-
8/8/2019 Salut Macro
35/41
fprintf(ser,'M%d\n',position);fprintf('M%d\n',position);
enddisp('End of program; servo off');fclose(ser);
How to write Matlab results to a text fileThis example opens 2 different files and writes different variables to each.
a = [1 2 3];b = [4 5 6];c = 7.94682e6;file_1 = fopen('output1.txt','w')file_2 = fopen('output2.txt','w')
fprintf(file_1,'Example formatted output \n\n')fprintf(file_1,'a = [%8.6E %8.6E %8.6E] (km/s)\n',a)fprintf(file_2,'b = [%13.6G %13.6G %13.6G] (km^3/s^2)\n\n c = %5.2f ',b,c)
fclose(file_1)fclose(file_2)
Notes:
o The conversion specifications are of the form %w.p
where w = minimum number of digits to be displayed
and p = precision (number of digits to right of decimal point)
f = floating point
E = exponential notation
G = automatic selection of f or E, whichever is more compact
d = integer
-
8/8/2019 Salut Macro
36/41
MATLAB Function Reference
fprintf
Write formatted data to file
Syntax
[count, errmsg] = fprintf(fid, format, A, ...)
Description
[count, errmsg] = fprintf(fid, format, A, ...) formats the data in the real part of
matrix A (and in any additional matrix arguments) under control of the specified format string,and writes it to the file associated with file identifierfid. fprintf returns a count of the number
of bytes written. errmsg is an optional output argument that returns an error message string if an
error occurred, or an empty string if an error did not occur.
Argument fid is an integer file identifier obtained from fopen. (It can also be 1 for standard
output (the screen) or2 for standard error. See fopen for more information.) Omitting fid causes
output to appear on the screen.
Format String
The format argument is a string containing C language conversion specifications. A conversionspecification controls the notation, alignment, significant digits, field width, and other aspects ofoutput format. The format string can contain escape characters to represent nonprinting
characters such as newline characters and tabs.
Conversion specifications begin with the % character and contain these optional and required
elements:
Flags (optional)
Width and precision fields (optional)
A subtype specifier (optional) Conversion character (required)
You specify these elements in the following order:
http://matlab.izmiran.ru/help/techdoc/ref/fopen.htmlhttp://matlab.izmiran.ru/help/techdoc/ref/fopen.htmlhttp://matlab.izmiran.ru/help/techdoc/ref/fopen.htmlhttp://matlab.izmiran.ru/help/techdoc/ref/frame2im.htmlhttp://matlab.izmiran.ru/help/techdoc/ref/fplot.htmlhttp://matlab.izmiran.ru/help/techdoc/ref/fopen.htmlhttp://matlab.izmiran.ru/help/techdoc/ref/fopen.html -
8/8/2019 Salut Macro
37/41
Flags
You can control the alignment of the output using any of these optional flags.
Character Description Example
Minus sign (-) Left-justifies the converted argument in its field %-5.2d
Plus sign (+) Always prints a sign character (+ or-) %+5.2d
Space character Inserts a space before the value % 5.2d
Zero (0) Pads with zeros rather than spaces %05.2d
Field Width and Precision Specifications
You can control the width and precision of the output by including these options in the format
string.
Character Description Example
Field width A digit string specifying the minimum number of digits to be printed %6f
Precision A digit string including a period (.) specifying the number of digits to be
printed to the right of the decimal point
%6.2f
Conversion Characters
Conversion characters specify the notation of the output.
Specifier Description
%c Single character
%d Decimal notation (signed)
%e Exponential notation (using a lowercase e as in 3.1415e+00)
%E Exponential notation (using an uppercase E as in 3.1415E+00)
%f Fixed-point notation
-
8/8/2019 Salut Macro
38/41
%g The more compact of%e or%f, as defined in [2]. Insignificant zeros do not print.
%G Same as %g, but using an uppercase E
%i Decimal notation (signed)
%o Octal notation (unsigned)
%s String of characters
%u Decimal notation (unsigned)
%x Hexadecimal notation (using lowercase letters a-f)
%X Hexadecimal notation (using uppercase letters A-F)
Conversion characters %o, %u, %x, and %X support subtype specifiers. See Remarks for more
information.
Escape Characters
This table lists the escape character sequences you use to specify nonprinting characters in a
format specification.
Character Description
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\\ Backslash
\'' or ''
(two single quotes)
Single quotation mark
%% Percent character
Remarks
http://matlab.izmiran.ru/help/techdoc/ref/fprintf.html#410667http://matlab.izmiran.ru/help/techdoc/ref/fprintf.html#410667 -
8/8/2019 Salut Macro
39/41
When writing text to a file on Windows, it is recommended that you open the file in write-text
mode (e.g., fopen(file_id, 'wt')). This ensures that lines in the file are terminated in such a
way as to be compatible with all applications that might use the file.
The fprintf function behaves like its ANSI C language namesake with these exceptions and
extensions:
If you use fprintf to convert a MATLAB double into an integer, and the double
contains a value that cannot be represented as an integer (for example, it contains afraction), MATLAB ignores the specified conversion and outputs the value in
exponential format. To successfully perform this conversion, use the fix, floor, ceil,
orround functions to change the value in the double into a value that can be represented
as an integer before passing it to sprintf.
The following nonstandard subtype specifiers are supported for the conversion characters%o, %u, %x, and %X.
b The underlying C data type is a double rather than an unsigned integer. For example, to
print a double-precision value in hexadecimal, use a format like '%bx'.
t The underlying C data type is a float rather than an unsigned integer.
For example, to print a double value in hexadecimal, use the format '%bx'.
The fprintf function is vectorized for nonscalar arguments. The function recycles the
format string through the elements ofA (columnwise) until all the elements are used up.
The function then continues in a similar manner through any additional matrix
arguments.
Note fprintf displays negative zero (-0) differently on some platforms, as shown in
the following table.
Conversion Character
Platform %e or %E %f %g or %G
PC 0.000000e+000 0.000000 0
Others -0.000000e+00 -0.000000 -0
Examples
Example 1
-
8/8/2019 Salut Macro
40/41
Create a text file called exp.txt containing a short table of the exponential function. (On
Windows platforms, it is recommended that you usefopen with the mode set to 'wt' to open a
text file for writing.)
x = 0:.1:1;
y = [x; exp(x)]; fid = fopen('exp.txt', 'wt');
fprintf(fid, '%6.2f %12.8f\n', y);
fclose(fid)
Now examine the contents ofexp.txt:
type exp.txt
0.00 1.00000000
0.10 1.10517092
...
1.00 2.71828183
Example 2
The command
fprintf('A unit circle has circumference %g radians.\n',2*pi)
displays a line on the screen:
A unit circle has circumference 6.283186 radians.
Example 3
To insert a single quotation mark in a string, use two single quotation marks together. For
example,
fprintf(1,'It''s Friday.\n')
displays on the screen
It's Friday.
Example 4
http://../techdoc/ref/fopen.htmlhttp://../techdoc/ref/fopen.htmlhttp://../techdoc/ref/fopen.html -
8/8/2019 Salut Macro
41/41
The commands
B = [8.8 7.7; 8800 7700]
fprintf(1, 'X is %6.2f meters or %8.3f mm\n', 9.9, 9900, B)
display the lines
X is 9.90 meters or 9900.000 mm
X is 8.80 meters or 8800.000 mm
X is 7.70 meters or 7700.000 mm
Example 5
Explicitly convert MATLAB double-precision variables to integer values for use with an integerconversion specifier. For instance, to convert signed 32-bit data to hexadecimal format,
a = [6 10 14 44];
fprintf('%9X\n', a + (a