Presentation is loading. Please wait.

Presentation is loading. Please wait.

Matrices and Arrays.

Similar presentations


Presentation on theme: "Matrices and Arrays."— Presentation transcript:

1 Matrices and Arrays

2 Creating Vectors A vector is a one-dimensional array of numbers. MATLAB allows creating two types of vectors: Row vectors Column vectors Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit the elements. For example,

3 r = [ ] MATLAB will execute the above statement and return the following result: r = Columns 1 through 4 Column 5 11

4 Column vectors are created by enclosing the set of elements in square brackets, using semicolon (;) to delimit the elements. c = [7; 8; 9; 10; 11] MATLAB will execute the above statement and return the following result: c = 7 8 9 10 11

5 Creating Matrices Entering Matrices
The best way for you to get started with MATLAB is to learn how to handle matrices. You can enter matrices into MATLAB in several different ways: • Enter an explicit list of elements. • Load matrices from external data files. • Generate matrices using built-in functions. • Create matrices with your own functions in M-files.

6 MATLAB Matrices MATLAB treats all variables as matrices. For our purposes a matrix can be thought of as an array, in fact, that is how it is stored. Vectors are special forms of matrices and contain only one row OR one column. Scalars are matrices with only one row AND one column

7 How to create a matrix in MATLAB
Separate the elements of a row with blanks or commas. Use a semicolon, ; , to indicate the end of each row. Surround the entire list of elements with square brackets, [ ]. Examples: A = [1, 4; 2, 5] or [1 4; 2 5] etc.

8 Generating matrices MATLAB treats row vector and column vector very differently A matrix can be created in MATLAB as follows (note the commas and semicolons) >> X = [1,2,3;4,5,6;7,8,9] X = Matrices must be rectangular! Note: In the matrix above X(2,3)= 6.

9 A scalar can be created in MATLAB as follows:
>> x = 23; A matrix with only one row is called a row vector. A row vector can be created in MATLAB as follows (note the commas): >> y = [12,10,-3] y = A matrix with only one column is called a column vector. A column vector can be created in MATLAB as follows: >> z = [12;10;-3] z = 12 10 -3

10 Extracting a sub-matrix
A portion of a matrix can be extracted and stored in a smaller matrix by specifying the names of both matrices and the rows and columns to extract. The syntax is: sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ; where r1 and r2 specify the beginning and ending rows and c1 and c2 specify the beginning and ending columns to be extracted to make the new matrix.

11 Example : >> X = [1,2,3;4,5,6;7,8,9] X = >> X22 = X(1:2 , 2:3) X22 = >> X13 = X(3,1:3) X13 = >> X21 = X(1:2,1) X21 = 1 4

12 % Make a matrix >> A = [1 2 3; 4 5 6; 7 8 9] ans: 1 2 3 4 5 6 7 8 9 % Access Individual Elements >> A(2,3) ans: 6 % Access 2nd column ( : means all elements) >> A(:,2) ans: 2 5 Array and Matrix Indices start at 1 not 0.

13 Matrix manipulation functions
zeros : creates an array of all zeros, Ex: x = zeros(3,2) ones : creates an array of all ones, Ex: x = ones(2) eye : creates an identity matrix, Ex: x = eye(3) rand : generates uniformly distributed random numbers in [0,1] diag : Diagonal matrices and diagonal of a matrix size : returns array dimensions length : returns length of a vector (row or column) det : Matrix determinant inv : matrix inverse eig : evaluates eigenvalues and eigenvectors rank : rank of a matrix find : searches for the given values in an array/matrix.

14 The Matrix in MATLAB A(2,4) A(17)

15 Array Operations in MATLAB
Arithmetic operations on arrays are done element by element. This means that addition and subtraction are the same for arrays and matrices, but that multiplicative operations are different. MATLAB uses a dot, or decimal point, as part of the notation for multiplicative array operations.

16 List of array operators
The list of operators includes + Addition - Subtraction .* Element-by-element multiplication ./ Element-by-element division .\ Element-by-element left division .^ Element-by-element power .' Unconjugated array transpose

17 Using arrays to build tables
Array operations are useful for building tables. Let us assume n is the column vector n = (0:9)'; Then pows = [n n.^2 2.^n] builds a table of squares and powers of 2: pows =

18 The Colon Operator The colon, :, is one of the most important MATLAB operators. It occurs in several different forms. The expression 1:10 is a row vector containing the integers from 1 to 10: To obtain non-unit spacing, specify an increment. For example, 100:-7:50 is and 0:pi/4:pi is

19 Plotting graphs MATLAB has many graphing capabilities. In many cases, customizing plots is desired and this is easiest to accomplish by creating a script. Typing help graph2d would display some of the two-dimensional graph functions, as well as functions to manipulate the axes and to put labels and titles on the graphs.

20 Plot of sin 5t t = 0: 2*pi/40: 2*pi; y = sin(5*t); plot(t,y)

21 Plot of sin t % This script plots sin(x) and cos(x) in the same Figure
% Window for values of x ranging from 0 to 2*pi clf x = 0: 2*pi/40: 2*pi; y = sin(x); plot(x,y,‘ro’) hold on y = cos(x); plot(x,y,‘b+’) legend(‘sin’, ‘cos’) title(‘sin and cos on one graph’)

22 Plotting graphs For a simple example of sin(5t), to graph it involves calculating the function at the points in the given interval. For a more complicated expression like z = etsin(5t), you have to calculate et and sin(5t) at each point and multiply them. This is called ARRAY MULTIPLICATION. To do this for z on e.g. [−1, 1] and n = 80, type t = −1 : : 1; z = exp(t).*sin(5*t) The .* indicates array multiplication. If you omit the period before the *, you will get an error message when you try to use the function.

23 For example, if we wish to plot xsin(3x2) e−x2/4 in the range [−π, π], we could type the following in the terminal window. x=-pi:pi/40:pi; y=x.*sin(3*x.ˆ2).*exp(-x.ˆ2/4); plot(x,y) The code listed above creates the row vector x, and then uses it to form a row vector y whose entries are the values of the function x sin(3x2) e−x2/4 for each entry in x. The operations preceded by a “dot,” such as .* or .ˆ are array operations. They allow entry-by entry multiplications or powers. Without the “dot,” these are matrix operations. After creating the arrays x and y, an x-y plot is made.

24 Plotting two functions on the same graph
To plot 2 functions, say w = tet and u = t3log(1 + |t|) on the same graph with e.g. the first a solid curve and the second with ’stars’, type t = −1 : 0.1 : 1; z = t. *exp(t) u = t.^3.*log(1 + abs(t)) and then plot(t, z, t, u, ” * ”).

25 Customizing a Plot: Color, Line Types, Marker Types
We can customize plots in MATLAB using various line markers or symbols and also various colors. The color choices available in MATLAB are: b blue c cyan g green k black m magenta r red y yellow

26 Marker types The plot symbols, or markers, that can be used are:
o circle d diamond h hexagram p pentagram plus point s square * star v down triangle < left triangle > right triangle ^ up triangle x x-mark

27 Line types Line types can also be specified by the following:
-- dashed -. dash dot : dotted - solid If no line type is specified, a solid line is drawn between the points.

28 A list of placeholders in MATLAB
Format Code Purpose %s Format as a string. %d Format as an integer. %f Format as a floating point value. %e Format as a floating point value in scientific notation. %g Format in the most compact form: %f or %e. \n Insert a new line in the output string. \t Insert a tab in the output string.

29 Simple Related Plot Functions
Other functions that are useful in customizing plots are clf, figure, hold, legend, and grid. Brief descriptions of these functions are given here. clf clears the Figure Window by removing everything from it. figure creates a new, empty Figure Window when called without any arguments. Calling it as figure(n) where n is an integer is a way of creating and maintaining multiple Figure Windows, and of referring to each individually.

30 hold is a toggle that freezes the current graph in the Figure Window, so that new plots will be superimposed on the current one. Just hold by itself is a toggle, so calling this function once turns the hold on, and then the next time turns it off. Alternatively, the commands hold on and hold off can be used. legend displays strings passed to it in a legend box in the Figure Window, in order of the plots in the Figure Window. grid displays grid lines on a graph. Called by itself, it is a toggle that turns the grid lines on and off. Alternatively, the commands grid on and grid off can be used.

31 linspace The linspace function has two advantages over the colon operator: (1) the endpoints of the axis and the number of points are entered directly as >> x = linspace(<first point>, <last point>, <number of points>) so it is much harder to make a mistake; and (2) round-off errors are minimalized so you are guaranteed that x has exactly n elements, and its first and last elements are exactly the values entered into the function.

32 Example sinncos.m % This script plots sin(x) and cos(x) in the same Figure % Window for values of x ranging from 0 to 2*pi clf x = 0: 2*pi/40: 2*pi; y = sin(x); plot(x,y,‘ro’) hold on y = cos(x); plot(x,y,‘b+’) legend(‘sin’, ‘cos’) title(‘sin and cos on one graph’)

33 2D Plotting >> x = linspace(0,2*pi,1000); % Creates regularly spaced vector. >> y = sin(x); >> z = cos(x); >> hold on; >> plot(x,y,‘b’); >> plot(x,z,‘g’); >> xlabel (‘X values’); >> ylabel (‘Y values’); >> title (‘Sample Plot’); >> legend (‘Y data’,‘Z data’); >> hold off; >> grid

34

35 Method 2: >> x = 0:0.01:2*pi; >> y = sin(x); >> z = cos(x); >> figure >> plot (x,y,x,z); >> xlabel (‘X values’); >> ylabel (‘Y values’); >> title (‘Sample Plot)’; >> legend (‘Y data’,‘Z data’); >> grid on;

36 Setting Axis Limits By default, MATLAB finds the maxima and minima of the data and chooses the axis limits to span this range. The axis command enables you to specify your own limits: axis([xmin xmax ymin ymax]) or for three-dimensional graphs, axis([xmin xmax ymin ymax zmin zmax]) Use the command axis auto to enable automatic limit selection again.

37 Using the subplot function
It can sometimes be useful to display multiple plots on the same figure for comparison. This can be done using the subplot function, that takes arguments for number of rows of plots, number of columns of plots, and plot number currently being plotted:

38 clear all close all % subplot (nrows, ncols, plot_number) x=0:0.1:2*pi; % x vector from 0 to 2*pi, dx = 0.1 subplot(2,2,1); % plot sine function plot(x, sin(x)); subplot(2,2,2); % plot cosine function plot(x, cos(x)); subplot(2,2,3) % plot negative exponential function plot(x, exp(-x)); subplot(2,2,4); % plot x^3 plot(x, x.^3);

39 Exercises Create a vector x with values ranging from 1 to 100 in steps of 5. Create a vector y that is the square root of each value in x. Plot these points. Now, use the bar function instead of plot to get a bar chart instead. Plot exp(x) for values of x ranging from –2 to 2 in steps of 0.1. Put an appropriate title on the plot, and label the axes.


Download ppt "Matrices and Arrays."

Similar presentations


Ads by Google