bett0099/matlab.doc · web viewmatlab can do complicated matrix mathematics and is useful for...
TRANSCRIPT
Matlab workshop
Our goal is to teach you enough so that you can learn a lot more on your own.
Introduction
Matlab is short for Matrix Laboratory. Matlab can do complicated matrix mathematics and is useful for processing large amounts of data. You can plot data and write programs to perform calculations.
Some menu commands:EditClear Command WindowClear Command HistoryClear Workspace
DesktopCommand Window—This is the console.Command History—You can run a command by clicking on it and pressing ENTER.Current Directory—You can run any M-files shown here. You can read files shown here.Workspace—Shows all of the variables currently in memory.Help
Window0 Command Window1 Command History2 Current Directory3 Workspace4 HelpEditor—Used to write programs.
HelpFull product family helpMATLAB HelpDemos—These are examples.
Help
Help for Matlab is useful. You can actually learn new things using Help. This handout covers a lot of topics in order to make you aware of what all there is to Matlab. Use Help to learn more.
Console
Type demo into the console to bring up examples (or go to Help→Demos)
You can do normal mathematical operations using the console (arithmetic, algebra, trigonometry, etc.).
Variables are stored in the workspace, where they can be viewed, changed, or deleted. You can also enter the command whos into the console to get a list of the current variables in the workspace
End a command with a semicolon if you don’t want Matlab to output the result right away.
Commands:clear will clear the workspace (you can clear only certain variables, for example, clear x y will clear variables x and y, and clear b* will clear all variables beginning with b)dir OR ls will list what's in the current directoryhelp ____ will tell you about _____whos will list the current variables… will continue a command onto the next line, so you can type a long command on multiple lines.
Data and variables
Variables can be scalars, arrays, matrices, cell arrays, or structure arrays. Arrays and matrices can only contain numbers, and each number must be the same data type (integer, floating point, etc.). Cell arrays are arrays where each element can be any sort of variable. You could have a cell array of matrices, integers, floating-point numbers, words, or any combination. Structure arrays are cell arrays where each cell is referred to by a name instead of by a number.
Matlab can perform operations on all the elements of a variable at once, e.g., you can take the sine of all the values of an array.
>> x = [0, pi/2, pi, 3*pi/2, 2*pi];>> sin(x)
ans =
0 1.0000 0.0000 -1.0000 -0.0000
Avoid pre-defined variable names:ans, pi, eps, flops, inf, NaN or nan, i, j, nargin, nargout, realmin, realmax(there are others)
Enter arrays as such: A = [1 2 3 4 5 6 7 8 9] or [1:9]You can also use commas instead of spaces: A = [1,2,3,4,5,6,7,8,9]
You can also use linspace: A = linspace(1,9,9)linspace(x1,x2,n) generates n numbers starting with x1 and ending with x2
Enter matrices as such:>> A = [1 2 3;4 5 6;7 8 9]
A =
1 2 3 4 5 6 7 8 9
Arrays can be combined to form matrices:>> x1 = [1 2 3];>> x2 = [4 5 6];>> x3 = [7 8 9];>> A = [x1;x2;x3];
A(x,y) accesses/changes the xth row and yth column.
You can access/change multiple elements at once: A(2,3:5) refers to the 3rd through 5th columns of the 2nd row.
A(:,1) refers to the first column.
A(1,:) refers to the first row.
A(1,:) = [] would delete the first row.
Arithmetic—can apply to matrices as well as scalars+ Addition- Subtraction* Multiplication/ Division\ Right division^ Exponentiation
Matrix arithmetic—see help topic Arithmetic Operations (Symbolic Math Toolbox section).* elementwise multiplication./ elementwise division.\ elementwise right division.^ elementwise exponentiation' transpose
Matrix functions—create matrices of dimensions m x n
zeroes(m,n) All elements zeroones(m,n) All elements oneeye(m,n) Diagonal elements = 1, other element = zero (identity matrix)rand(m,n) All elements random from 0 to 1randn(m,n) All elements randomly drawn from standard normal distribution
Strings:Sometimes you may want to use a variable with alphanumeric characters. This is called a string. If you bound a set of characters with apostrophes, Matlab will recognize it as a string.
>> first_name = ‘Simeon’;>> last_name = 'Poisson';>> full_name = [first_name,' ',last_name]
full_name =
Simeon Poisson
You can also combine strings with the strcat function, though this ignores trailing spaces and stand-alone spaces:>> full_name = strcat(first_name,' ',last_name)
full_name =
SimeonPoisson
Saving your work:save file_name—Saves the variables in your Workspace (might need to put a .mat extension on the filename)load file_name—Loads the variables into your Workspace.save file_name variable1 variable2—Saves only the specified variable(s) (you can do the same thing with load)save file_name.txt –ASCII—Saves Workspace into text file that you can read with a word processor or text editor. You will not be able to load the Workspace from a text file.
Plotting
Use plot to plot data. You can set the color, symbol, axes labels, axes ranges, title, and legend. You can plot many sets of data on the same graph, or even show multiple graphs.
Plotting commandsplot(x1,y1,'string1', x2,y2,'string2',…) Plots x1 on the x-axis and y1 on the y-axis with
appearance specified by string1. Likewise for x2, y2, and string2, etc.
xlabel('string') Adds x-axis label to plotylabel('string') Adds y-axis label to plottitle('string') Adds title to plotlegend('string1','string2',…) Adds legend to plot, with string1 corresponding
to x1,y1, string2 corresponding to x2,y2, etc.hold on OR hold off (see below)text(x,y,'string') Puts the string at the coordinates x,ygtext('string') Puts the string at coordinates specified by
clicking with the mousegrid on OR grid off Adds/removes gridlinessubplot(m,n,i) Fills in the ith plot of a subplot that has m rows
and n columnsxlim([x1 x2]), ylim([y1 y2]) Sets minimum/maximum values for x or y axesaxis([x1,y1,x2,y2]) Sets minimum/maximum values for x or y axes
Try this:>> x = linspace(0,(2*pi),21);>> y = sin(x);>> z = cos(x);>> plot(x,y,'bx');
The 'bx' specifies that the points should be blue x's. We can specify a variety of colors, symbols, and line types:
Color Plot symbol Line typeb blue . point - solidg green o circle : dottedr red x x-mark -. dashdotc cyan + plus -- dashedm magenta * stary yellow s squarek black d diamond
v triangle (down)^ triangle (up)< triangle (left)> triangle (right)p pentagramh hexagram
We can add another plot like so:
>> hold on>> plot(x,z,'bo');
If we hadn't used hold on, we would have replaced the first plot instead of adding to it.You can also plot multiple items at once just by using one plot command.
>> hold off>> plot(x,y,'bx',x,x.^2,'gx');
Now let's try labeling and customizing this plot:>> title('two functions');>> xlabel('x');>> ylabel('y');>> legend('sin(x)','x^2');>> xlim([0 6.5]);>> ylim([-2 40]);>> grid on
3D plotting commandsplot3(x,y,z)meshgridsurf
Programming
If you don’t know anything about programming, Matlab might be a good place to learn. M-files are Matlab programs, and they use the .m file extension. Just type the filename into the console (without the .m at the end) to run the program. Avoid using spaces in the filename, or you won't be able to run it from the console. You can use the Matlab editor (or any text editor or word processor that outputs a plain ASCII text file) to write m-files.
You can only run M-files that are listed in the working directory or in the one of the directories in the “Set Path” list.
M-files can be functions or scripts.
FunctionsA function has one or more inputs and one or more outputs. You can write your
own functions when programming. In Matlab, the function name and the file name must match (though the filename will have that additional .m at the end).
Example function:Create an m-file named example.mWrite the following lines in the file:
function [x, y]=example(a,b)%This is an example functionx = a + b;y = a * b;
Now test out your function in the console:>> [m,n] = example(2,3)
m =
5
n =
6
Everything that happens inside the function is independent of the Workspace. Commands inside the function are only aware of variables passed to the function or created within the function. Variables created within the function are destroyed when the function ends.
ScriptsSuppose we remove the first line of that example function:
%This is an example scriptx = a + b;y = a * b;
Now we have a script instead of a function. Commands inside the script are aware of the variables in the Workspace, and variables created by the script are added to the Workspace. Everything happens as though you had typed the commands into the console.
Beginning a line with a % will make the line a comment. Comments are not executed. They are useful for writing notes to yourself or to anyone else who might use your program.
A simple and short function can also be made into an inline function instead of writing an m-file:
>> f1=inline(‘x^2 + 1’)
f1 =
Inline function: f1(x) = x^2 + 1
>> f1(2)
ans =
5
Here is a template that you might find useful if you are working with large or complex functions and want to document your work for yourself or others:
function function_name( input_variable );%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% AUTHOR:% DATE:%% PURPOSE%% INPUT%% OUTPUT%% DESCRIPTION OF LOCAL VARIABLES%% FUNCTIONS CALLED%% START OF EXECUTABLE CODE%
if statementsAn if statement will execute a set of commands if a particular condition is true.
if condition_1command_1
elseif condition_2command_2
…elseif condition_n
command_nelse
last_commandend
The conditions can be statements such as:x < 1 (x greater than 1)
x > 1 & x < 2 (x greater than 1 and less than 2)x < 1 & x > 2 (x less than 1 or greater than 2)x ~= 1 (x not equal to 1)
These conditions include Logical operators and Boolean operators
Logical operators== equal to> greater than>= greater than or equal to< less than<= less than or equal to~= not equal to
Boolean operators& And (elementwise)| Or (elementwise)&& And (scalar only)|| Or (scalar only) ~ or not() Not&& and || are called short-circuit operators because they will only check the second part of the expression if necessary.
Entire arrays vs. single elementsIf you put an array or matrix variable in a condition statement and do not refer to
a single element of that variable, Matlab will not inform you of your mistake except when using && and || (in which case you will get an error message). This mistake can screw up your if statements.
To illustrate, try the following:
>> a = [1 1 2];>> b = [1 2 2];>> a(1)==2 & b(1)==2
ans =
0
>> a==2 & b==2
ans =
0 0 1
These are very different results that will probably be interpreted differently by an if statement.
While LoopsA while loop executes a set of commands over and over as long as a condition is true.
while condition_1command_1
end
For LoopsA for loop executes a set of commands a set number of times.
sum1 = 0;for i=1:10
sum1 = sum1 + x(i);end
sum1 now equals the sum of integers 1 through 10.
You can terminate any loop with a break command. Note that if you have a break command inside an if statement inside a loop, it will still terminate the loop.
Switch-Case statementIf you have a variable that can take several discrete values and want to execute different sets of commands for different values of that variable, you can use a switch-case statement. You could do the same thing with an if statement, but this is usually easier to write out.
switch variable_namecase value_1
command_1case value_2
command_2…case value_n
command_notherwise
other_commandend
example:x = 2;switch ccase ‘square’
result = x^2;
case ‘cube’result = x^3;
case ‘sin’result = sin(x);
otherwiseresult = 0;
end
File I/O
Sometimes you want to read a file or output a file.fopen('name') opens a file and returns a file IDfclose(fid) Closes file specified by fid. fclose(‘all’) closes all open filesfprintf will print to a file, or to the console if no file is specifiedtextscan useful for reading in large text files, e.g. text files with columns of data
Try the following (you can enter this into a script or into the console):fid = fopen('myfile.txt','w');%Opens file for writing (this will erase the file if it already exists)fprintf(fid, 'Test File:\n');for i = 1:10 fprintf(fid, 'The number %g\n', i);endfclose(fid);%closes the file referred to by fid
Now you should have the file myfile.txt in your current directory. It should look like this:Test File:The number 1The number 2The number 3The number 4The number 5The number 6The number 7The number 8The number 9The number 10
If you use Notepad to view the file, it probably won't display the line breaks correctly, but Wordpad will.
You could put myfile.txt anywhere if you specified the full file path:fid = fopen('C:\Documents\Matlab\myfile.txt','w');
Explanation of fprintfWe used the following statement to write to the file:fprintf(fid, 'The number %g\n', i)
fid specifies what file to write to. If you omit this, it will write to the console instead. The string specifies what to write, with the \n indicating a line break. The %g is used to insert a variable of fixed-point or exponential notation. The i specifies what variable to write in place of the %g.
You can write multiple variables with one fprintf. If the statement was:fprintf(fid, 'The number %g%g%g\n', i, i, i)
then it would write the following if i = 1:The number 111
Look up fprintf on Help to learn more.
Built-in Functions
Here are a handful of Matlab’s built-in functions:abs—absolute valuefindstr—looks for one string within anotherfprintf—can print to screen or to a fileinput—gets input from the user (useful in some programming applications)int2str—changes and integer into a string data typeisnumeric—returns 1 if variable is numeric, 0 if notlength—returns the length of an arraymean—returns averageprctile—find percentile of an arraysize—returns the size of a matrixsqrt—returns square rootstd—returns standard deviationstrcat—concatenates stringsstrcmp—compares two strings and returns 1 if they are the same, 0 if they are not
If you want to do some sort of standard mathematical operation, Matlab probably has a function for it (eigenvalues, standard deviation, etc.).
Equation solving
If you are interested in equation solving, here is an example to get you started.
>> g=solve ('(b/a)=1.4248148', 'sqrt(a^2+b^2)=1')
g =
a: [2x1 sym] b: [2x1 sym]
>> g.a ans = .57447577397592445397436691096785 -.57447577397592445397436691096785 >> g.b ans = .81852158500235200570459679537727 -.81852158500235200570459679537727
The function solve outputs a structure array, in this case g. g has two cells, a and b, each of which is an array with two elements. The notations g.a and g.b refer to cells a and b, respectively.
Some additional topics not covered
Solving ordinary differential equationsIntegration
References
Kelso, Frank (2007) Primer on Matlab: Introductory Session Notes. (handout during class)
Mardan, Setareh (2005) Matlab: An Introductory Short Course. (handout during Matlab short course)