Matlab Commands Math 2250 Fall 2011 Created by Victor Camacho This file discusses several commands and functions in Matlab that will be very useful in Math 2250/2280 courses. If you have any additional suggestions for what could be added to this file feel free to let me know. If you are not already familiar with Matlab, I would suggest first reading the Introduction to Matlab1 file to familiarize yourself with the basic properties. The instructions in this file assume you are already familiar with how to login to your account, open Matlab, enter basic commands into Matlab, create an m-file, save an m-file, and execute an m-file. I would highly suggest trying out all of the commands in this document to familiarize yourself with them. Many of these commands will be helpful for doing the assigned projects as well as checking your work on homework and other problems. Help: Any time you need help in Matlab you can go to the "Help" menu and select "Product Help". This will open a new window with, among other things, a search box where you can enter the subject you need help with, or the specific command. If you already know the name of the function you wish to use, such as the "sqrt" function, you would type the following text onto the command line: >> help sqrt The output of this command will be essentially everything you need to know about the square root function, it will also provide links to related functions and documentation. Comments: In many circumstances you may find it useful to insert comments into your Matlab code. In an m-file you may have many lines of code that do different things. It will be useful to remind yourself what each parts of the code does. Matlab will automatically ignore all of the text you have entered on a line after a percentage symbol (%). Everything entered on the line after this symbol will be colored green, to indicate that it is a comment and will not be read by Matlab. Consider the following commands that have been entered into an m-file: 1 http://www.math.utah.edu/~camacho/teaching/fall2011/files/Matlab_Intro.pdf ------------------------------------------------------% In this file I calculate the hypotenuse of a triangle. % 1. Define the length of the two legs of the triangle a = 3; b = 4; % 2. Use the Pythagorean theorem to calculate the length % of the hypotenuse. c = sqrt(a^2 + b^2); % 3. Output the final answer. c ------------------------------------------------------- Notice how the use of comments helps you understand exactly what the program is doing at every step. Even if you're not entirely familiar with all of these commands yet. Every line that starts with a % symbol is interpreted as a comment and colored green. Also notice the use of white space here. Matlab does not care how many lines separate each command or comment, so you can separate your code into distinctive chunks if you need to in order to help your understanding. Finally, notice that all but the last command ends in a semi-colon. If you want the result of a specific command to be displayed, you can remove the semi-colon, otherwise Matlab will suppress the output. This is generally a good idea for m-files since there will be many commands but you will typically only care about the end result. Variables and Arithmetic In Matlab it is possible to assign a value to a given variable. Suppose you wanted to set the letter a to the value of 2. You would simply enter >> a = 2 Now, anytime you use the letter a (by itself) it will be interpreted as the number 2. For example, Matlab will correctly compute all of the following arithmetic operations with a: >> a + 1 >> a^3 >> sqrt(a) % This outputs a plus 1, "ans=3" % This outputs a cubed, "ans=8" % This outputs square root of a, "ans=1.4142" >> abs(a) % This outputs the absolute value of a, "ans=2" You can subsequently change the value of a by reassigning it to a different value. After typing the following command, a will now have a value of 3 anytime it is used (until it is reassigned): >> a = 3 You can also reassign the value of a using an expression in terms of a. Consider the following commands: >> a = a + 1 % This sets a+1 as the new value of a. So if % previously a had a value of 3, it now has a % value of 4. >> a = 2*a % This will double the current value of a and set % that to the new value of a. >> a = sqrt(a) % This will take the square root of the current % value of a and set that to the new value of a. Matlab is fairly flexible with the names of variables. You are basically allowed to use any string of letters (both upper and lower case), numbers, and underscores. The only restriction to this is that the string MUST start with either an upper or lower case letter. All of the following would be valid variable names in Matlab: a, a1, a_12, applepie, apple_pie, axq4350dkdfjks, q1123443342, a___c4. Matlab has a few of its own internally defined variables and functions that you will not be able to assign in your code. These include things like pi, i, sin, cos, log, exp, abs, sqrt, and so on. Matlab Functions Matlab has many internally defined functions for you to use when doing various computations. The functions may be prepared to receive one or more arguments. The general format for calling a function is as follows: >> function_name(argument1) >> function_name(argument1, argument2) >> function_name(argument1, argument2, argument3) You first write the function name, then open parenthesis, then the list or arguments that the function will receive, where each argument is separated by a comma, and then close the parenthesis. Let's look at a few examples: >> sin(0) % The sin function only has one argument. % command will compute the sine of 0. This >> nthroot(8,3)% % % % The nthroot function requires two arguments, the first argument is the radicand and the second argument is the index. This command will compute the cube root of 8. >> mod(20,6) The mod function also requires two arguments, the function will take the first argument modulo the second argument. So here we are computing 20 mod 6 which is 2. % % % % If at any time you were not sure how many arguments a particular function receives, or which argument represents which quantity, you can always use the help command. For example, to get more details about the nthroot() function type the following command: >> help nthroot Some Matlab functions may receive a different number of arguments depending how you wish to use that function. For example, the zeros() function is used to create a matrix where all the entries are zeros, and the arguments help specify the dimensions of the matrix. If this function only receives one argument, it will assume you want a square matrix of the specified dimensions. If this function receives two arguments, it will assume the first argument represents the number of rows and the second argument represents the number of columns. Consider the following two commands: >> zeros(5) >> zeros(4,2) % This creates a 5x5 matrix of all zeros % This creates a 4x2 matrix of all zeros You can use Matlab's help command to read about the zeros() function. Defining Vectors and Matrices One of the primary uses of Matlab is to work with vectors and matrices. You can construct them manually, or you can use some of Matlab's built-in functions to help you. Let's first discuss how to construct these objects by manually. Row vectors are constructed by enclosing the entries in square brackets, and separating each entry by a space or comma. For column vectors you will do the same, except that the entries will be separated by semicolons. Observe the following three commands: >> [1 2 3] % Row vector >> [1, 2, 3] % Row vector >> [1 ; 2 ; 3] % Column vector Matrices are constructed similarly. The entries are all enclosed inside square brackets. The entries in each row of the matrix are separated by spaces or commas, and each row of the matrix is ended by a semicolon. Here are two ways of constructing the 2x2 identity matrix in Matlab: >> [1 0 ; 0 1] >> [1, 0 ; 0, 1] % 2x2 Identity Matrix % 2x2 Identity Matrix The first command below will create a 3x2 matrix while the second command creates a 2x3 matrix. >> [1 2 ; 3 4 ; 5 6] >> [1 2 3 ; 4 5 6] Matlab has several built-in commands and functions to help you create special types of vectors and matrices quickly. In Matlab, the colon symbol (:) is used to construct incremental row vectors. That is, row vectors where each entry increments by a fixed value as you proceed through the row. When the command is of the form "a:b", the value of a is the first entry of the vector, and the vector is constructed so that each additional entry is one plus the previous entry, until you reach the value of b (without going over the value of b). Consider the following commands >> 1:4 >> -3:2 >> 1:4.5 % Constructs the vector [1 2 3 4] % Constructs the vector [-3 -2 -1 0 1 2] % Constructs the vector [1 2 3 4] When the command is of the form "a:c:b", the same rules apply as before, except, instead of incrementing each entry by 1, the entries are incremented by the value of c. Notice that c may be a negative number in which case the entries of the vector become progressively smaller. In this case it is necessary that the value of a greater than the value of b. Consider the following examples: >> 0:2:8 % Constructs the vector [2 4 6 8] >> 0:0.5:2 % Constructs the vector [0 0.5 1 1.5 2] >> 4:-1:0 % Constructs the vector [4 3 2 1 0] There are many useful functions in Matlab that help you create special types of matrices. Try out any of the following: >> >> >> >> >> >> zeros(3) zeros(5,8) ones(4) ones(2,5) eye(6) rand(3,4) % % % % % % % Constructs a 3x3 matrix of all zeros Constructs a 5x8 matrix of all zeros Constructs a 4x4 matrix of all ones Constructs a 2x5 matrix of all ones Constructs the 6x6 identity matrix Constructs a 3x4 matrix whose entries are random numbers between 0 and 1. Once you have constructed a vector or matrix, it is possible to access the entries in the matrix. The following example illustrates how to do this: >> A = eye(3) % Assigns A to be the 3x3 identity matrix >> A(2,2) % Outputs the entry in the second row and second % column of A, "ans=1". >> A(1,3) % Outputs the entry in the first row and third % column of A, "ans=0" You can also reassign the values of specific entries of a matrix. Consider the following example: >> A = eye(3) % Assigns A to be the 3x3 identity matrix >> A(2,2) = 4 % Now the value in the second row and second % column of the matrix A is set to 4. The rest % of the matrix is unchanged. For vectors the commands are very similar, however, you only need to specify a single argument for the entry number, rather than a row number and a column number. Consider the following commands: >> v = [1 2 -1 3] % Assigns v to the row vector [1 2 -1 3] >> v(3) % Outputs the value in the third entry of % the vector v, which in this case is -1. >> v(3) = 2 % Sets the value of the third entry in v to % 2. So now v = [1 2 2 3]. Suppose that instead of displaying only one entry in a vector, you want to display the contents of several consecutive entries of a vector. Here is how you would do that: >> v = [1 2 -1 3 4 10 32 1 -6 2 7 5] >> v(3:5) % % % % Outputs the 3rd, 4th and 5th entry of the vector v. In other words, it outputs every entry in v between and including the 3rd entry and 5th entry. >> v(1:6) % Outputs every entry in v between and including the % 1st entry and 6th entry. Similar syntax is used to display partial matrices. Consider the following examples: >> A = eye(6) % Assigns A to be the 6x6 identity matrix >> A(2:4,3:5) % Displays all entries that are both within the % 2nd and 4th rows of A and the 3rd and 5th % columns of A. Note that this partial matrix % should be a 3x3 matrix >> A(3,:) % % % % Displays the entire third row of A. Notice that the ":" symbol in this case tells Matlab to refer to ALL entries in this dimension of the matrix. >> A(:,4) % Displays the entire 4th column of A. >> A(2:4,:) % Displays the matrix consisting of the entire 2nd, % 3rd and 4th rows of A. Matrix and Vectors Operations and Functions Matlab is capable of doing operations on matrices and vectors using its large library of built in functions. Let's begin by defining two matrices and a vector which we will then perform several operations on. Based on the discussion in the previous section, you should be able to figure out what each of these matrices and vectors look like. >> A = [1 2 ; 3 4] % A is a 2x2 matrix >> B = [1 0 ; -1 1] % B is a 2x2 matrix >> v = [1 2] % v is a 2x1 vector As long as two matrices have the same dimension, you can add and subtract them. However, a dimension mismatch will return an error in Matlab. Errors are always displayed in red text. >> A + B >> A - B >> A + v % % % % Adds A and B. Subtracts B from A. Returns an error in Matlab because of the dimension mismatch. Multiplication in the form of scalar-matrix, scalar-vector, matrix-matrix and matrix-vector are all straightforward in Matlab. Once again an error will be returned if there is a dimension mismatch according to the rules of matrix multiplication. In the five examples below there should be no errors. >> >> >> >> >> 5*A 3*v A*B A*v A^3 % % % % % Multiplies Multiplies Multiplies Multiplies Raises the the scalar 5 by the scalar 3 by the matrix A by the matrix A by matrix A to the the matrix A. the vector v. the matrix B. the vector v. power of 3. There are several functions built-in to Matlab that perform operations or give you information about matrices and vectors. Below we demonstrate how to use some of the more important builtin functions. >> inv(A) % Returns the matrix inverse of A >> det(A) % Returns the determinant of A >> eig(A) % Returns the eigen values of A % The output is presented as a column vector. >> [E D] = eig(A) % % % % Stores the eigenvalues of A as a column vector into the variable E. Stores the eigenvectors of A as the columns of a matrix into the variable D. >> size(A) % Returns the number of rows and columns of A. % The output is presented as a row vector. >> length(v) % Returns the length (number of elements) of % the vector v. >> A' % Returns the transpose of A. >> v' % Returns the transpose of v. >> sum(v) % Returns the sum of all entries in v. >> max(v) % Returns the maximum value of all entries in v. Another very useful feature in Matlab is its component wise arithmetic operations. Suppose that instead of multiplying two matrices or vectors in the conventional way, you simply want to multiply them component-wise. Or, suppose that instead of raising a matrix to the fourth power, you instead want to raise every entry of the matrix to the fourth power. Every component-wise operation in Matlab looks similar to the conventional operations except they are preceded by a period. Consider the following commands >> A = [1 2 ; 3 4] >> B = [1 0 ; -1 1] >> A.*B % This command will output the matrix that results % from multiplying A and B component-wise. >> A.^2 % This command will output the matrix that results % from squaring each entry of A. Note that this is % different than squaring the matrix A (multiplying A % by itself) For-Loops Matlab has a really cool feature which allows you to repeat a similar process many times. The basic idea is to define an index variable that starts counting from a certain number and continues until it reaches another number. For each different value that the index takes on, Matlab will do a certain task that you specify. Let's take a look at the following example which would be entered into an m-file. ---------------------------------------------------------------% The for loop below simply tells Matlab to output the value of % the index at each iteration. The "for" command instructs % Matlab that you are about to define a for-loop. The syntax % "i=1:5" means that you are defining your index to be "i" and % that the index will start counting at 1 and continue until it % gets to 5. The "end" command tells Matlab where the for-loop % ends. Matlab understands that all of the code enclosed % between the "for" command and the "end" command describe this % for-loop. for i=1:5 i % This will simply tells Matlab to output the current % value of i end % The for-loop will repeat until i=5. ---------------------------------------------------------------Save this m-file as whatever name you choose and then execute that file (by typing the name of the file, without the .m extension, onto the command line). Matlab will output the value of i at each iteration. The output after each iteration should look like: i = 1 This output will be displayed one after the other for all iterations from 1 to 5. You can have Matlab do much more complicated tasks than simply displaying the index number of each iteration. Suppose you wanted to find the sum of the first 100 integers. The following m-file will accomplish this when executed. ---------------------------------------------------------------% This program will output the sum of the first 100 integers. s = 0; % The variable s will represent the running total. We % need to start at 0. Notice that the output of this % line is suppressed. for i=1:100 % We will need to go through 100 iterations for % this. The index, i, will take on the value of % each integer between 1 and 100. s = s+ i; % Take the current value of s and add it to % current index, then store that sum to be % the current value of s. Effectively, we start % with s=0 and add every consecutive integer to it % between 1 and 100. end % Repeat the loop until i=100 s % After the loop has finished running, you want to % display the current value of s, as it now represents % the sum of the first 100 integers. ---------------------------------------------------------------Let's now look at a slightly more complicated example. Suppose you wanted calculate the first 100 Fibonacci numbers and store them in a vector. Recall that the Fibonacci sequence can be defined by the following iterative formula: , , where is the nth Fibonacci number. The following program calculates the first 100 Fibonacci numbers, stores them into a vector, and then outputs the vector. ---------------------------------------------------------------F = zeros(100,1); % % % % Define a column vector, called F, which will be used to store the first 100 Fibonacci numbers. We can set all entries of this vector to 0 for now. F(1) = 1; % The first Fibonacci number defined to be 1. F(2) = 1; % The second Fibonacci number defined to be 1. for n=3:100 % % % % % % We will need to use the iterative Fibonacci formula to calculate the 3rd through the 100th Fibonacci number. That is why we start at 3. Just to be fancy, we'll use "n" as our index instead of "i". In principle you can use any variable name you want. F(n) = F(n-1) + F(n-2); % % % % Apply the iterative Fibonacci formula to find the current Fibonacci number using the previous two Fibonacci numbers. end F % After the loop has finished running, you want to % display the values stored in the vector F, which % should be the first 100 Fibonacci numbers. ---------------------------------------------------------------- If-Loops If loops are conditional statements in Matlab. The commands within an if-loop are only executed when a certain condition is met. For example, suppose that you have define a for-loop, and that you want something different to happen depending on whether your index is even or odd. Here is one way to do this: ---------------------------------------------------------------% The for-loop below simply tells Matlab, at each iteration, to % output the value of the index, but only when the index is % even. Notice that the if loop must be enclose by the keywords % "if" and "end. The conditional statement of the if-loop is % enclosed in parenthesis after the "if" keyword. The double % equal sign "==" is the comparison operator, which is different % than the assignment operator, "=". When you want Matlab to % compare two quantities and say whether or not they are equal, % you use the "==" operator. When you want to assign a variable % to a value, you use the "=" operator. for i=1:10 if ( mod(i,2) == 0) % If i is even... i % display the current value of i end end ---------------------------------------------------------------In addition to the comparison operator, "==", there are several other operators to be aware of. They include: "<", ">", "<=", and ">=", which are the standard inequality comparison operators. In some cases you may want to run an if loop if two things are NOT equal. The comparison operator for this is "~=". For example, suppose you only want Matlab to evaluate a rational function, but only for values of x in the domain of the rational function. In this case there is perhaps only one value of x for which you do not want the function to be evaluated, and in all other cases the function should be evaluated. To see how you might implement something like this, consider the following example: ---------------------------------------------------------------if (x ~= 1) % If x is not equal to 1. y = 1/(x-1); % Evaluate the function at the given value % of x. end ---------------------------------------------------------------A slight extension to the if-loop is the if-else-loop. It may be useful, in some circumstances, to have the program do one thing if the conditional statement is true, and something else if the conditional statement is false. For example, suppose you have a piecewise function that is defined as when and when . Here is how you could program Matlab to output the correct value, given a value of x: ---------------------------------------------------------------if (x < 0) y = x^2; else % If x is less than 0. % Evaluate the function using the definition % corresponding to negative values of x. % Otherwise y = x; % Evaluate the function using the definition % corresponding to non-negative values of x. end ---------------------------------------------------------------- Defining Your Own Function In Matlab it is possible, and in many circumstances very useful, to define your own functions. The standard protocol is to use an entire m-file to define one function. You want the name of the function to match the name of the m-file. The below m-file is an example of how you would define a function f(), which takes one argument, x, as its input, and then outputs a value called y, which, in this case, is the square of x. ---------------------------------------------------------------% This function takes a single value as its input, called x, and % outputs a value that is the square of the input, called y. % The user will specify the value of x when they use the % function. function y = f(x) y = x^2; % % % % % % % On this line you use the function command to define the beginning of the function. This line tells Matlab that your function is called, "f", it has one input argument, called "x", and it will output value of "y" when the function is finished executing. % Define the value of y to be the square of x. end % This tells Matlab that the function definition ends here. % When arriving at this line, Matlab will output the % current value of "y". ---------------------------------------------------------------Once you finish entering the above syntax in an m-file, you will want to save it as "f.m". That is, you want the name of the m-file (minus the .m extension) to match the name of the function. To use this function, you can type a command such as the following >> f(5) % % % % % % >> f(10) % This command should output "ans=100" >> f(f(2)) % % % % This will call your function, setting the input, x, to 5. It will then calculate the output, y, based on that input value, and then it will display the output. So the output for this command should be "ans=25", since your function simply took the number 5 and squared it. This command will first evaluate f(2), and then use that output as the input for the function f(), just as function composition works. The output of this command will be "ans=16". Since Matlab is equipped to handle matrices and vectors, just as easily as it can handle single numbers, Matlab will not complain if you input a square matrix into f(). Consider the following commands: >> A = [1 2 ; 3 4] >> f(A) % This command will square the matrix A and output the % resulting matrix. The function f() that we defined above is a very simple example of a function. In principle on can easily define a more complicated function, with more possible input arguments. To demonstrate the concept of having multiple input arguments, consider the following function: ---------------------------------------------------------------% This function takes as its input the coordinates of a point in 3-space, and calculates the distance of that point from the origin. % % % % % % The first line uses the function command to tell Matlab that you are beginning to define a function. The name of the function is "dist", the name of the output is "d", and there are three input variables called "x", "y", and "z". The function will output the value assigned to "d" at the time it is finished executing. function d = dist(x,y,z) d = sqrt(x^2+y^2+z^2); % Calculate the distance from the % origin and assign that value to the % variable "d". end ---------------------------------------------------------------Save this text to an m-file and call the m-file "dist.m", so that the name of the file matches the name of the function. To use this function on the command line you would use the following syntax: >> dist(3,4,5) % % % % The dist() function is prepared to accept three input arguments, so you must specify all three when executing this function on the command line. Function Handles In the previous section you learned about how to define functions in Matlab. These functions can be entire blocks of Matlab code and may be extremely complicated if you would like them to be. They can also output plots and text etc. In many cases, however, you may only want to define a function that carries out a simple mathematical operation. Say for example you want to define a function that takes the square of the input, without creating an entire m-file. You can do this using function handles. Consider the following example: >> f = @(x) x^2; % In this line you have assigned f to be a % function with one argument, x, whose % output is simply the square of the input. >> f(5) % This calls the function f(), using the % input x=5, so the output should be % "ans=25". Let's break down the first command above. We are assigning the variable f to be a function handle. A function handle always starts with the @ symbol, following by the list of input variables for the function which are enclosed in parenthesis and separated by commas. After the list of input variables is the instructions for how to use the input variables to calculate the output. As you may have guessed, it is possible to have multiple input variables, as in the following example: >> f = @(x,y) x*y; >> f(2,3) % Defines the function f(x,y) which outputs % the product of the two input variables. % This calls the function f(), using the % inputs x=2 and y=3, so the output should be % "ans=6". As with everything else in Matlab, the input arguments for these function are not required to be numbers, they can be vectors or matrices. Suppose you wanted to define a function t() which takes a matrix as its input and outputs the product of that matrix with its transpose. This could be accomplished with the following command: >> t = @(A) A*A'; % Multiplies the input matrix by its % transpose, and outputs the product. As a general note, it is not necessary to use capital letters for matrices and lower case letters for vectors and numbers. In theory you can give a matrix any name you want that is a valid Matlab variable. However, you will want to develop your own consistent naming scheme for your variables that will help you keep track of them easily. One standard practice is to use upper-case letters for matrices. Numerical Solver As you know, there are many equations that cannot be solved algebraically. In these circumstances it is useful to use a numerical solver. Fortunately, Matlab has a built in way to solve equations numerically. Suppose you wanted to find the solution to the equation . You will not be able to find the solution algebraically. To solve this problem you will want to rearrange the equation so that everything is on one side, and is equal to zero. In other words, you want to solve the equivalent equation . If we define the function , then solving this equation is equivalent to finding the roots of . This is the form in which Matlab will be able to solve this problem, it can find the roots of arbitrary functions. You will begin by defining a function handle in Matlab, which is the function you would like to find the root of. Then you will use Matlab's fzero() function to find the root, as follows: >> f = @(x) x - exp(-x); % Define our function in Matlab using a % function handle. >> fzero(f,0) % % % % % % % % The first argument in fzero() is the function handle itself. The second argument is your best guess as to where the root of the function actually is. We will put zero for now since we don't know any better. Though inspecting the graph of f(x) may lead us to a better estimate. Matlab should output a very close numerical approximation to the answer. Display Text In many circumstances it is desirable to have Matlab display the output of a function or program in a specific way. As you may have noticed by now, Matlab's default style for outputting is not always ideal. Here we explain how to customize the output that Matlab produces. The disp() function is used to display a string of text in the Matlab output. A string of text must be enclosed in two apostrophe symbols. Try out the following command: >> disp('Hello, World!') Note that the string is highlighted purple automatically in Matlab, so that you can distinguish it from other commands or variables. The output of this line will be the text "Hello, World!", and it will be displayed on the next line, there is no line break between the command prompt and the output. It is possible to concatenate multiple strings together, this is done by combining the strings as elements of a vector. Consider the following command >> disp(['Welcome', 'to', 'Matlab']) The vector has three elements, each of which are strings. Matlab interprets this as one long string, in which the three strings have been concatenated. The disp() function then displays the resulting string in the output. The output here should be "WelcometoMatlab". Notice the lack of spaces, that is because you didn't define any, Matlab did a direct concatenation of the strings you entered. The disp() can also display numbers and data structures. The way it is displayed is slightly more flexible than the standard Matlab output as it does not include as many line breaks or white space. Try out the following commands in Matlab. >> >> >> >> x = 5; A = [1 2 ; 3 4] disp(x) disp(A) The number and matrix are displayed more compactly than Matlab normally would. The limitation of the disp() function is that it can only display one type of data at a time. That is, is can only display a string, or only a number, but it cannot display both types of data at the same time. What you must do if you want to display numerical data and string data simultaneously is to first convert the number to a string and then concatenate it with another string. Use the num2str() command to convert a number to a string. This command can take one or two arguments as inputs. The first argument is always the number you want to convert, and the second is the number of significant digits to display. Consider the following commands. >> >> >> >> >> str2num(5) % str2num(3.44) % str2num(1/3) % str2num(1/3,2) % str2num(sqrt(2),2) Outputs the string '5'. Outputs the string '3.44'. Outputs the string '0.33333'. Outputs the string '0.33'. % Outputs the string '1.4'. Now if you want to display a number with a string or in the middle of the string you could do so as follows: >> >> >> >> >> x=3; y=7; disp(['The answer is ',num2str(x)]) disp(['I worked ',num2str(y),' hours today.']) disp(['x=',num2str(x),', y=',num2str(y)]) Notice how in the above examples, vectors are used to concatenate strings. Then the disp() function displays the entire string as the output. This is very convenient for displaying the final results of a function or program you have written in a way the is easy to read. Plotting Matlab uses the plot() function to create plots of data. The plot() function requires at least two arguments (inputs), though it will accept more if you wish to describe the formatting of the plot. The first argument specifies the x-values of each point you wish to plot (in the form of a vector), and the second argument specifies the corresponding y-values of each point you wish to plot. Consider the following example >> x = [1 2 3]; >> y = [8 9 10]; >> plot(x,y) % % % % % This will plot the points (1,8), (2,9) and (3,10) and, by default, will join these three points with a line. The plot window will automatically be adjusted to fit all three points. Notice that the plot function plots each ordered pair in the x and y vectors. That is, the first element in the x vector is paired with the first element in the y vector to form an ordered, pair. Then the second element in each vector form the second ordered pair, and so on. Each ordered pair is then graphed and the points are connected with a line in the order they appear. The above example is great for plotting individual points. In some cases, you may be interested in plotting an actual function. While there is no standard way to do this in Matlab analytically, you can certainly improvise. Let's say you want to plot the function in the domain [0, 1]. You'll want to create a vector x which has many points between 0 and 1 that are closely spaced together. Then define another vector y whose components are the square of the corresponding components of x. Here is how you could do this >> x = 0:0.01:1 % % % % This creates a vector whose first element is 0 and then each element is incremented by 0.01 until you reach 1. The resulting vector is stored in the variable x. >> y = x.^2 % % % % This will create a vectors whose components are the square of each corresponding component of x. The resulting vector is stored as y. >> plot(x,y) This will plot 101 points that exist on the graph of the function , and each point will be connected by a line. While this is not an exact graph of the function, the points are so closely spaced together that it will be difficult for your eye to notice the difference. If you do notice that the graph is a little choppy, you can instead make the points in the x vector be spaced by only 0.001, or 0.0001. The plot() function accepts a third argument that specifies how you want the data to be displayed. The third argument is a string that has a few different characters that are used by Matlab to determine whether or not you want a line to be drawn, what marker you want to use for the line, and what color you want the lines and markers to be. Consider the following examples >> x = [1 2 3]; >> y = [4 5 6]; >> plot(x,y,'-.b') % % % % % % % The first character, "-", specifies that you want a line to connect each point, the second character, ".", indicates that you want a small dot as the marker for each point, and the third character, "b" specifies that you want the line and markers to be colored blue. >> plot(x,y,'-.r') % This plot will look the same as above % except it will be colored red. >> plot(x,y,'-.g') % This plot will look the same as above % except it will be colored green. >> plot(x,y,'-ob') % This plot will look the same as the first % one except each marker will be a small % circle instead of a point. >> plot(x,y,'-xb') % This plot will look the same as the first % one except each marker will be a small % "x" instead of a point. >> plot(x,y,'.b') % % % % Since the dash has been omitted, the points will be plotted with blue dot markers, but no line will be connecting them. >> plot(x,y,':xr') % % % % In this case a dotted line will be connecting the points, the markers will be a small "x", and the markers and dotted line will be colored red. In addition to graphing certain functions, there are also easy ways to label your axis and give your graph a title. You can also set the viewing window of your plot. See how this is done in the following example: >> x = [1 2 3]; >> y = [4 5 6]; >> plot(x,y,'-.b') >> xlabel('Year'); >> ylabel('Cost') >> title('Annual Cost') % Label the x-axis "Year" % Label the y-axis "Cost" % Title the graph "Annual Cost" >> axis([0 10 0 10]) % % % % % Set the limits for the viewing window of the plot. The vector here means [xmin xmax ymin ymax]. So in this example both the x-axis and y-axis range from 0 to 10. These are a few of the options available. Consult the Matlab help menu for further details. Putting it all together In this last section I've written a program that puts many of the above ideas together to approximate the solution to the logistic population growth equation using the forward Euler method. ---------------------------------------------------------------T = [0 5]; dt = 0.01; % Specify the start and end time in this vector. % Specify the time step. M = 1000; k = 0.00003; P0 = 10; % Specify the carrying capacity. % Specify the parameter k. % Specify the initial population. t = T(1):dt:T(2); % Define time vector P = zeros(size(t)); % Define the population vector P(1) = P0; % Store the initial population value in the % population vector. for i = 2:length(P) % % % % We have already specified the value for the first time point, now we want to calculate the value for all of the others. dPdt = k*P(i-1)*(M-P(i-1)); % Use the previous value of P to % calculate the derivative of P % using the differential equation. P(i) = P(i-1) + dt*dPdt; % Use the forward Euler formula to % calculate the updated value of % P. end plot(t,P,'-.b'); % Plot P as a function of t disp('Logistic Population Growth'); disp('Forward Euler Method'); disp(['M = ',num2str(M)]); disp(['k = ',num2str(k)]); disp(['dt = ',num2str(dt)]); disp(['P0 = ',num2str(P0)]); disp(['t = [',num2str(T(1)),', ',num2str(T(2)),']']); disp(['P(' ,num2str(T(2)), ') = ', num2str(P(length(P)))]); ---------------------------------------------------------------- Summary This should serve as a great introduction to Matlab. You are now familiar with essentially all of the commands you will need for Math 2250 and Math 2280. There are many Matlab commands that were omitted from this file, and others that were included but not explained in full detail. All of this explored further through the Matlab help file or the Matlab demo videos.