Matrices and Arrays.

Slides:



Advertisements
Similar presentations
Introduction to M ATLAB Programming Ian Brooks Institute for Climate & Atmospheric Science School of Earth & Environment
Advertisements

Plotting Selim Aksoy Bilkent University Department of Computer Engineering
Introduction to Matlab
Lecture (4) Plotting & Programming (1) Eng. Osama Talaat 1.
Introduction to Graphing Using MATLAB. Line Graphs  Useful for graphing functions  Useful for displaying data trends over time  Useful for showing.
Matlab Graphics S. Awad, Ph.D. M. Corless, M.S.E.E. E.C.E. Department University of Michigan-Dearborn Introduction to Matlab: 2D Graphics.
Matrix Manipulation and 2D Plotting
MA/CS375 Fall MA/CS 375 Fall 2002 Lecture 4.
MATLAB - Lecture 22A Two Dimensional Plots / Chapter 5 Topics Covered:
Vectors and Plotting Selim Aksoy Bilkent University Department of Computer Engineering
Lecture 2 MATLAB fundamentals Variables, Naming Rules, Arrays (numbers, scalars, vectors, matrices), Arithmetical Operations, Defining and manipulating.
Introduction to MATLAB MECH 300H Spring Starting of MATLAB.
Plotting. Basic Plotting Two vectors of x and y values needed. Vectors need to be of the same length, but not necessarily of the same geometry. For example,
Matlab intro The Environment
Part 1 Chapter 2 MATLAB Fundamentals
MATLAB Fundamentals.
What is MATLAB ? MATrix LABratory –Originally, it was a front-end to FORTRAN matrix routines developed in the U. of New Mexico and Stanford –Today.
Chapter 5 Review: Plotting Introduction to MATLAB 7 Engineering 161.
MATLAB INTRO CONTROL LAB1  The Environment  The command prompt Getting Help : e.g help sin, lookfor cos Variables Vectors, Matrices, and Linear Algebra.
ENG College of Engineering Engineering Education Innovation Center 1 2D Plots 1 in MATLAB Topics Covered: 1.Plotting basic 2-D plots The plot()
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
ELG 3120 Signal and System Analysis 1 Introduction to MATLAB TAs Wei Zhang Ozgur Ekici (Section A)(Section B) ELG 3120 Lab Tutorial 1.
ECE 1304 Introduction to Electrical and Computer Engineering Section 1.1 Introduction to MATLAB.
INTRODUCTION TO MATLAB LAB# 01
Matlab Basics Tutorial. Vectors Let's start off by creating something simple, like a vector. Enter each element of the vector (separated by a space) between.
Lecture 2 - Matlab Introduction CVEN 302 June 5, 2002.
ES 240: Scientific and Engineering Computation. Chapter 2 Chapter 2: MATLAB Fundamentals Uchechukwu Ofoegbu Temple University.
Matlab Screen  Command Window  type commands  Current Directory  View folders and m-files  Workspace  View program variables  Double click on a.
Part 1 Chapter 2 MATLAB Fundamentals PowerPoints organized by Dr. Michael R. Gustafson II, Duke University and Prof. Steve Chapra, Tufts University All.
Recap Chapter 5 “Plotting” Two Dimensional Plots Simple x-y Plots Titles, Labels and Grids Multiple Plots.
EGR 106 Lecture 6 2-D Plotting Graphical presentation has become the standard method to show technical information. Engineers use plots to analyze, visualize,
Introduction to Matlab  Matlab is a software package for technical computation.  Matlab allows you to solve many numerical problems including - arrays.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS ( NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS (PRACTICAL PART) Lab 2 : potting to Matlab Networks.
CS100A, Fall 1998, Lecture 191 CS100A, Fall 1998 Lecture 19, Thursday Nov 05 Matlab Concepts: Matlab arrays Matlab subscripting Matlab plotting.
CS100A, Fall 1998, Lecture 201 CS100A, Fall 1998 Lecture 20, Tuesday Nov 10 More Matlab Concepts: plotting (cont.) 2-D arrays Control structures: while,
Outline What is MATLAB MATLAB desktop Variables, Vectors and Matrices Matrix operations Array operations Built-in functions: Scalar, Vector, Matrix Data.
EGR 106 – Week 5 – 2-D Plots Question : Why do engineers use plots? Answer : To analyze, visualize, and present data. Matlab has many useful plotting options.
How to use MATLAB (using M-files) Double click this icon To start Matlab 6.5.
Prof. N. P. Jadhav Presented by. Overview of MATLAB environment MATLAB is an interactive, matrix-based system for scientific and engineering numeric computation.
ECE 1304 Introduction to Electrical and Computer Engineering
Creating a Plot The plot function can take one or more inputs; e.g. plot (x, y) or plot (y) Note that in the two-argument version, the vectors x and.
Manipulating MATLAB Matrices Chapter 4
Computer Application in Engineering Design
Introduction to Mat lab
3D-Graphs A 3D surface is defined as: z = f(x, y)
Lecture 25: Exploring data
Introduction to Programming for Mechanical Engineers (ME 319)
MATLAB DENC 2533 ECADD LAB 9.
Introduction To MATLAB
Net 222: Communications and networks fundamentals (Practical Part)
Net 222: Communications and networks fundamentals (Practical Part)
Net 222: Communications and networks fundamentals (Practical Part)
EEE 244 Numerical Methods In Electrical Engineering
Part 1 Chapter 2 MATLAB Fundamentals
MATLAB How to use (using M-files) Double click this icon
MATH 493 Introduction to MATLAB
Use of Mathematics using Technology (Maltlab)
MATLAB How to use (using M-files) Double click this icon
MATLAB How to use (using M-files)
Introduction to MATLAB Plotting LAB 3
INTRODUCTION TO MATLAB
Introduction to MATLAB
Plotting Signals in MATLAB
Part 1 Chapter 2 MATLAB Fundamentals
244-2: MATLAB/Simulink FUNDAMENTALS
Announcements P3 due today
How to Use MATLAB A Brief Introduction.
Introduction to Matlab
Matlab Basics Tutorial
Presentation transcript:

Matrices and Arrays

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,

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

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

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.

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

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.

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 = 1 2 3 4 5 6 7 8 9 Matrices must be rectangular! Note: In the matrix above X(2,3)= 6.

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 = 12 10 -3 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

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.

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

% 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 8 Array and Matrix Indices start at 1 not 0.

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.

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

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.

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

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 = 0 0 1 1 1 2 2 4 4 3 9 8 4 16 16 5 25 32 6 36 64 7 49 128 8 64 256 9 81 512

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: 1 2 3 4 5 6 7 8 9 10 To obtain non-unit spacing, specify an increment. For example, 100:-7:50 is 100 93 86 79 72 65 58 51 and 0:pi/4:pi is 0 0.7854 1.5708 2.3562 3.1416

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.

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

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’)

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 : 0.025 : 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.

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.

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, ” * ”).

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

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

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.

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.

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.

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.

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.

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’)

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

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;

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.

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:

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);

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.