Matlab Demo 1Matlab OverviewAbout MatlabMatlab stands for Matrix Laboratory. It started out as a scripting language developed by graduate student Cleve Moler so he could use LINPACK subroutines without having to write a Fortran program for each calculation. Cleve Moler later founded MathWorks, which continues to expand and market Matlab. Matlab has by now absorbed most of the public domain scientific computation software, and has its own programming language and graphing system. There are interfaces to programming language, the Excel spreadsheet, scientific instruments, and much more. There is also an add-on called Simulab for circuit simulation. Data TypesThe data types we are likely to encounter in this class are double (numbers), char (strings), sym (symbolic variables), inline (inline function), function_handle (function handles), and many others we don't need.
There are others, and you can also develop your own (object-oriented programming). Type double includes complex numbers. Structures and Cell Arrays (optional)Standard arrays are written A(i,j). They consist of elements of the same type (array of double, or array of char). A cell array is written A{i,j}. Its elements can have different types. A = {1,[2,3],'hello'} is a 1x3 cell array with elements that are a scalar, a vector, and a string. A{2} = [2,3], so A{2}[2] = 3, and so on. A structure is a one-dimensional cell-array whose subscripts are text, not numbers. A standard example in programming courses is an employee record:
This is basically the same as a cell array { 'James Smith', '(515) 555-1234', 60000}, except that the subscripts are 'name', 'phone' and 'salary' instead of 1,2,3. Constants and Variables
All matrices start with subscript 1. Matlab is case sensitive, but don't rely on that. Certainly not with script or function files on Windows systems (file names are not case sensitive in Windows). Predetermined Variablesi Basic Matricesx = zeros(3,4) StatementsSeparated by comma, end of line, or semicolon. Continuation statements: y = x + ... Important Commandshelp <function> Basic Arithmetic Functionsc = a + b Caution: they all work in matrix sense A±B % A, B must be matrices of same size, or scalars Pointwise Arithmetic Functions on MatricesC = A .* B Standard functions all work element by element: C = sin(A), cos(A), exp(A), log(A), etc. Use Vector/Matrix NotationTo write good Matlab programs, you have to learn to think in terms of entire vectors and matrices, not in terms of element-by-element computations. Your programs will be shorter and run faster. Bad: for i = 0:100 Good: x = 0:0.1:10; Matrix Concatenation
The Colon Operator and Matrix Subscripting1:10 = [1,2,3,4,5,6,7,8,9,10]; Colon-generated lists are used often in subscripting and loops: A(1:3,2:3) = the 3x2 submatrix taken from rows 1-3, columns 2 and 3 In subscripting, a single colon means "from beginning to end". You can also use the string end. A(:,2) = second column Control Structures
Plottingplot(x,y) % connect the dots Multiple plots in one picture:
Text is interpreted as in TeX (simple cases only, like greek letters, subscripts)
All graphics commands can be executed in the form h = command. h is the handle and can then be manipulated. WorkspaceThe workspace is the set of all variables that you defined. Each function gets its own workspace. Scripts, Functions and SubroutinesI learned programming in Fortran. Fortran has functions and subroutines. The difference is that a function returns a value, and a subroutine does not. Matlab makes no distinction between functions and subroutines. I think the Matlab documentation does not even use the word subroutine, but it you ever run across it, it means the same as function. Matlab instead makes a distinction between scripts and functions. Script:
Function:
Both scripts and functions are stored as files with .m extension on the computer. If the file starts with the word "function", it is a function. Otherwise, it is a script. script.m: x = 5; f.m
Call them from main program: x = 3; General form: function [out1,out2,...] = f(in1,in2,...) All input arguments go on the right. All output arguments go on the left. Input and output arguments can have the same name. Functions can be called with more or fewer input or output arguments than defined. Nothing bad happens as long as you don't try to use an undefined value. Examples: function [y1,y2] = f(x1,x2) called as y = f(1,2) % y2 is thrown awayThe following example shows a function norm(x,p) which calculates the p-norm of the vector x. If p is not given, use p=2. This is what the actual built-in norm command does. function y = norm(x,p) Here is an example with a variable number of outputs. This is how the actual built-in command size works:
Advanced example: s = sum(a,b,c,...) % unknown number of arguments function s = sum(varargin) Inline Functions These can be used for simple, one-line functions, if you don't want to deal with making up a file for them.
If you have more than one variable, list the variables at the end in the correct order, just to make sure. Note that an inline function operates in its own workspace. In the following example, the variable a is undefined inside the inline function:
Function Handles Function handles were developed to pass functions as arguments. Suppose you have a function f, stored in a file f.m, and you want to numerically integrate it from 1 to 3. The integration routine is called quad (for "quadrature"). Old style: area = quad('f',1,3); The function name is passed as a string. the problem with that is that if the quad routine internally uses a variable called x1, and your function happens to be called x1, this bombs. New style: fun = @f; area = quad(fun,1,3); fun is now a function handle. This is now the recommended way, but the old way still works. As a side effect, you can define function handles that point to functions that are defined inline, instead of in an external file. Notice that this time a has a value, but it is not dynamic. Inside g, a is replaced by its value at the time when g was defined.
Most of the time, inline functions and function handles behave identically. Paths and Shadowed FunctionsWhat actually happens when you type x = a?
There could be several routines a.m in the path. The order of directories in the path determines which one gets executed. When you type x = a(3), the same thing happens. This could be the third element in array a, or function a evaluated with argument 3.
Passing Functions as ArgumentsOld method: minimum = fmin('f',[a,b],x0) % find minimum of f on interval [a,b] with initial guess x0 The problem is that if function fmin contains a variable called f, you get weird errors. New method: fhandle = @f; % function handle Alternative:
Another Alternative:
The following used to work. Maybe it still does. I still wouldn't recommend it. minimum = fmin('x.^2-2*x+1',[a,b],x0); Fun and GamesAll versions of Matlab contain some "easter eggs", that means, hidden jokes. Unfortunately, most of them have disappeared over the years. Still present in version 7:
Jokes that I observed myself in the past: Unfortunately, they have been removed from recent versions.
The lalala command can be simulated with these commands: Puts up a picture of a sports car. Jokes that other people have reported that I have not observed:
Supposedly these commands just make appropriate noises. Last Updated: January 15, 2009 |