University of Delaware



Introductory Matlab Examples

WCR 2012-02-12

This file is a set of Matlab commands and explanatory comments. It is designed to illustrate Matlab for a first-time Matlab user. Read file matlabintro.html before doing the examples in this file. The examples were done using Matlab version 2012b, but they will work the same way in other versions as well. The following commands can be typed into the Matlab command window.

|Command window. Input typed by the user is bold. |Explanation |

| | |

|>> clear all |Clear all variables from Matlab’s memory. |

|>> clc |Clear the Matlab command window. |

|>> 3+2 |Evaluate and display arithmetic results |

|ans = | |

|5 | |

| | |

|>> a=5 |Assign the value 5 to the variable “a”. Since “a” does not already |

|a = |exist in Matlab’s workspace, it will be created. Matlab’s workspace |

|5 |will be cleared and forgotten when this instance of Matlab is closed. |

| |A semicolon afer a command suppresses the display of the results. |

|>> a=5; |Assign the value 3 to it. b will be created since it does not yet |

| |exist. Since the command did not end with a semicolon, the result is |

|>> b=3 |displayed. |

|b = | |

|3 |Evaluate and display a times b. |

| | |

|>> a*b | |

|ans = | |

|15 |Assign the result of a times b to the variable c. |

| | |

|>> c=a*b | |

|c = | |

|15 |Assign the value “the quick” to the variable s. Note that s is a |

| |string variable. |

|>> s='the quick' | |

|s = | |

|the quick |Compute and display sin(a). |

| | |

|>> sin(a) | |

|ans = | |

|-0.9589 |Assign the value exp(b) to the variable d. Since there is no semicolon|

| |at the end of the command, the result is displayed. |

|>> d=exp(b) | |

|d = | |

|20.0855 | |

| | |

|>> a=[1 3 7] |Assign the values [1,3,7] to a. a is a “row vector” containing 3 |

|a = |elements. Spaces or commas are used to separate columns. |

|1 3 7 | |

| |Assign the value [1;3;7] to b. Semicolons separate rows in Matlab, so|

|>> b=[1;3;7] |b, defined with semicolons, is a column vector with 3 rows. |

|b = | |

|1 | |

|3 | |

|7 |An apostrophe character after a variable tells Matlab to “transpose” |

| |the variable (turn rows into columns and vice versa). Since b is a |

|>> c=b' |column vector, b’ (pronounced “b prime” or “b transpose” by linear |

|c = |algebra mavens) is a row. |

|1 3 7 |Transpose a and assign the resulting value to d. Since a is a row |

| |vector, a’ is a column vector. |

| | |

|>> d=a' | |

|d = | |

|1 | |

|3 |This command is an unsuccessful attempt to create a 3x3 array of |

|7 |numbers. It fails because semicolons are used where spaces or commas |

| |should be used. When Matlab interprets this command, it sees two rows|

|>> a=[1 3 7;5 9 2;13;24;9] |with three elements per row, followed by three rows with one element |

|Error using vertcat |per row. Arrays must have the same number of elements in each row, so|

|Dimensions of matrices being concatenated are not |this command generates an error message. |

|consistent. | |

| |Here is a correct command to create a 3x3 array of numbers. |

| | |

| | |

| | |

|>> a=[1 3 7;5 9 2;13 24 9] | |

|a = |Display transpose of a. Note that the diagonal elements do not change|

|1 3 7 |when the rows and columns are flipped. |

|5 9 2 | |

|13 24 9 | |

| | |

|>> a' | |

|ans = |Add a column to the 3x3 array a, and assign the resulting array to b. |

|1 5 13 | |

|3 9 24 | |

|7 2 9 | |

| | |

|>> b=[a [4; 6; 8]] |size(b) returns the number of rows and columns in b. The number of |

|b = |rows is always first. |

|1 3 7 4 | |

|5 9 2 6 | |

|13 24 9 8 | |

| | |

|>> size(b) | |

|ans = | |

|3 4 | |

| | |

|>> [r c]=size(b) |Compute size of b and assign the results to the variables r and c. (b|

|r = |has 3 rows, 4 columns) |

|3 | |

|c = | |

|4 | |

| | |

|>> [r c]=size(d) |Compute size of d and assign the results to the variables r and c. d |

|r = |is a column vector , i.e. it has several rows and a single column. |

|3 | |

|c = | |

|1 | |

| |Compute size of transpose of d and assign the values to the variables |

|>> [r c]=size(d') |r and c. |

|r = | |

|1 | |

|c = | |

|3 | |

| |This shows how to access individual elements within an array (or |

|>> b(1,1) |vector). The row and column of the desired element are given in |

|ans = |parentheses. b(1,1) returns the value in the first row, first column |

|1 |of the array b. |

| | |

| |Get the value in row 3, column 2 of b. |

|>> b(3,2) | |

|ans = | |

|24 | |

| |Here is the entire array b. Compare to results of previous two |

|>> b |commands. |

|b = | |

|1 3 7 4 | |

|5 9 2 6 | |

|13 24 9 8 | |

| |Multiply the array d by 1.5 and assign the result to e. When an array|

|>> e=1.5*d |is multiplied by a number , each element is multiplied by that number,|

|e = |and the result is the same size as the original array. By the way: a |

|1.5000 |number can be thought of as a “1x1” array (pronounced “one by one”). |

|4.5000 |A number is often referred to as a scalar in linear algebra. |

|10.5000 | |

| |Add the arrays d and e and assign result to f. Arrays can only be |

| |added or subratced if they are the same size. If you try to add or |

| |subtract matrices that are of different sizes, you will get an error |

|>> f=d+e |message. |

|f = | |

|2.5000 | |

|7.5000 |A matrix can be negated, element by element. It is the same as |

|17.5000 |multiplying by negative one. |

| | |

|>> c=-b | |

|c = | |

|-1 -3 -7 -4 | |

|-5 -9 -2 -6 | |

|-13 -24 -9 -8 | |

|>> g=c+3*b |Add three time b to c and assign the result to g. |

|g = | |

|2 6 14 8 | |

|10 18 4 12 | |

|26 48 18 16 | |

| | |

|>> h=g(:,1:3) |Here we see the “colon operator” for the first time. The colon |

|h = |operator is very useful in Matlab. When it appears by itself in place|

|2 6 14 |of a row or column specifier, in means “all the rows” or “all the |

|10 18 4 |columns”. This command says “get all the rows, and columns 1 through |

|26 48 18 |3, of matrix g, and assign the result to h”. |

| |Another example of the colon operator. This command also shows how to|

|>> i=g(:,[1,4]) |retrieve non-contiguous columns from an array. The same idea works |

|i = |for rows too. This command says “get all the rows, and columns 1 and |

|2 8 |4, of matrix g, and assign the results to i”. |

|10 12 | |

|26 16 |Another example of the colon operator. This command syas “ get row 2,|

| |and all the columns, of g, and assign the result to j. |

|>> j=g(2,:) | |

|j = | |

|10 18 4 12 | |

The next section shows how to get data into and out of Matlab, from and to external files. All information in the Matlab workspace is lost when Matlab is closed, so if you have generated results worth saving, you can do so using the methods shown next.

| | |

|>> a=load('tmc_sim1.txt','-ASCII') |Load data from file “tmc_sim1.txt” into Matlab’s workspace, |

| |and save the information in the variable a. This will only |

| |work if the file specified is in the current directory or is |

| |“on the path”, i.e. in a directory which in in the list of |

| |directories that make up Matlab’s current “path” or list of |

| |directories to search. Use the Matlab help to learn more |

| |about how to set the path variable. The entry ‘-ASCII’ in the |

| |load command tells Matlab that the file specified is a text |

| |file. |

| | |

| |a now has 971 rows and 3 columns of data. |

|>> size(a) | |

|ans = | |

|971 3 | |

| |Here we introduce the “input” command. It is useful in Matlab|

|>> filename=input('Enter name of file: ','s') |programs when you need to get information from the user. Here |

|Enter name of file: tmc_sim1.txt |the user is prompted to enter the name of a file. The user |

|filename = |typed in “tmc_sim1.txt” (without quotes). The result is saved |

|tmc_sim1.txt |in the variable filename. The ‘s’ in the input command tells |

| |the input function to expect a string rather than a number. |

| |Since the command did not terminate with a semicolon, the |

| |result is displayed. |

|>> a=load(filename,'-ASCII'); |The load command is used again. This time the variable |

|>> size(a) |filename (without quotes) is used to specify the name of the |

|ans = |file from which to load data. The size command shows that |

|971 3 |that a has 971 rows and 3 columns, as it did after the |

| |previous load command. |

| | |

| | |

| | |

| |We use Matlab to do something with the data we have loaded.. |

|>> b=2*a; |In this case we simply multiply it by two. Notice that it |

|>> size(b) |takes a single, simple command to multiply all 971 rows and 3 |

|ans = |columns by 2. |

|971 3 | |

| |Display rows 1 through 3, and all columns, of b. |

| | |

|>> b(1:3,:) | |

|ans = | |

|0 0 60.0000 | |

|0.6000 0 60.0000 | |

|1.0000 0 60.0000 |Display rows 1 through 3, and all columns, of a. |

| | |

|>> a(1:3,:) | |

|ans = | |

|0 0 30.0000 | |

|0.3000 0 30.0000 | |

|0.5000 0 30.0000 |“save” is another very important command. The contents of |

| |variable b are saved in file saved_b.txt. The entry ‘-ASCII’ |

|>> save('saved_b.txt','b','-ASCII') |tells Matlab to save the data as a text file. |

|>> | |

The next section shows how to make plots with Matlab. We only show the basics here. You can make plots with multiple panels, and you can add annotation and other elements to plots. See the online help for more information.

First we create some data to plot.

|>> t=[0:.3:1] |Here we show how to create a sequence of values. This command says |

|t = |“create a sequence of numbers starting with 0 and proceeding in steps |

|0 0.3000 0.6000 0.9000 |of 0.3 up to a maximum of 1; assign the result to t. |

| | |

| |Create a vector with the numbers 0 to 1 in steps of .01. |

|>> t=[0:.01:1]; | |

| |Compute the sine of two time pi times each value in the vector t. |

|>> x=sin(2*pi*t); |Assign the result to x. Semicolon suppresses the display of the |

| |results. x will be the same size as t. |

| | |

| |Compute vector y=cos(4*pi*t). |

|>> y=cos(4*pi*t); | |

Now that we have some interesting data, let’s plot it.

|>> plot(t,x) |Plot t on horizontal axis and x on vertical axis. x and t must |

| |have the same length. If not, an error message will appear. The |

| |plot appears in a new window. |

| |Plot t versus y. This overwrites the previous plot. |

|>> plot(t,y) |This tells Matlab to hold the data in the current figure, so that|

|>> hold on |the next plot command will add to the figure instead of |

| |overwriting it. |

| |Add a plot of x versus t to the figure. |

|>> plot(t,x) |Add gridlines. |

|>> grid on; |Add x axis label. |

|>> xlabel(’Time (s)’); |Add y axis label. |

|>> ylabel(’Position (cm)’); |Add title. |

|>> title(’My Plot’); |Add legend (labels for each data series). |

|>> legend(’cos(4*Pi*t)’,’sin(2*Pi*t)’); | |

| |Create a new empty figure window. |

|>> figure; |Use ’kx’ to make plot with black x symbols. This also shows |

|>> plot(t,sin(2*pi*t),'kx'); |that one can use a Matlab function instead of a variable name in |

| |a plot command. Here we use sin(2*pi*t) instead of x. |

| | |

| |Replot with red * symbols, and lines connecting the points. |

| | |

|>> plot(t,sin(2*pi*t),'r*-'); |Add a plot of cosine that uses blue + symbols and no connecting |

| |lines. |

|>> hold on; |Add grid. |

|>> plot(t,cos(2*pi*t),'b+'); |Add legend (labels for each data series). |

| |Add x axis label. |

|>> grid on; |Add y axis label. |

|>> legend(’sine’,’cosine’); |Add title. |

|>> xlabel('Time (s)'); | |

|>> ylabel('Velocity (cm/s)'); | |

|>> title('My Second Plot'); | |

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download