Linear Algebra and MATLAB - Badarinzabadarinza.net/download/christian/slides4.pdf ·...

19

Transcript of Linear Algebra and MATLAB - Badarinzabadarinza.net/download/christian/slides4.pdf ·...

Linear Algebra and MATLAB

Pre-Semester Course Mathematics

Christian [email protected]

MATLAB1

1This script is based on a MATLAB course of Alexey Cherepnev and Tobias

Nagel at University of Mainz.

Outline

I Plotting 2D

I Plotting 3D

I Subplots

The function plot

I Easiest way to visualize results

I Draws lines through points

Syntax

�plot(X,Y)�⇒ Plots vector Y against vector X .

�plot(X1, Y1, S1)�⇒ Plots vector Y 1 against vector X1 into one �gure. S1 is astring, specifying the line type

Introductory example: Plotting a ploynomial:

We want to develop a function which1) evaluates a given ploynomial of degree ≤ 32) plot this ploynomial

eval_poly3.m

function out = eval_poly3(a,x)% Evaluates a polynomial up to degree 3 at x% Input: a - coefficients (4-dim vector)% a(1)*x 3̂+a(2)*x 2̂+a(3)*x+a(4)% x - evaluation points (number or vector)% Output: values of polynomialif (size(a,2)==1 | size(a,1)==1)if (size(a,2)==4 | size(a,1)==4)out = a(1).*x. 3̂+a(2).*x. 2̂+a(3).*x+a(4);

elseerror(’Wrong dimension of a. Wrong amount of entries’);

endelse

error(’Wrong dimension of a. Not a vector’);

end

�Good� practice in programming

Your code should be easy to read and as easy as possible to follow.

I Use comments, esp. an introductory comment

I Use indentation and �white spaces� to structure your code

I Names should be self-explaining and / or �speaking� names

I Use parentheses even when MATLAB knows precedence

More details and tips:http://www.mathworks.com/matlabcentral/�leexchange/2529

Plotting

Now we plot a polynomial, e.g. x3 + 2x2 + 3x + 4:

» x = -30:10:30;» coeff = 1:4;» y = eval_poly3(coeff,x);» plot(x,y);

⇒ Connection of 7 points - too coarse (rede�ne x)

Additional arguments to produce clear plots

Change linetyp: �plot(x,y,’linetype’)�

Color:y yellowb bluer redg greenk blackc cyanm magenta

Symbols:◦ circlex x-mark+ plus

* stars squared diamond> / < triangle

Line style:- solid (default): dotted-. dash-dotted−− dashed

'linetype' can be a combination of those symbols

Additional arguments to produce clear plots cont.

Some more commands:

figure(n) Opens an additional�gure window denoted as�Figure n�

hold on / off Holds current �gure windowlegend(’fun1’, ’fun2’,...) Adds a legendgrid Inserts grid legendaxis(x1,x2,y1,y2) Sets range of axistitle Adds titlexlabel Adds label on x-axisylabel Adds label on y-axis

⇒ You can also customize your graphic through a GUI

Plotting cont.

How to get two or more graphs into one graphic

Two ways:

I plot(x1,y1,’linetype1’,x2,y2,...’linetype2’ [, ...]);

I Commands to customize graphic ('title', 'xlabel', y'label','legend', 'axis') as usual

I plot(x1,y1,’linetype1’);hold on;plot(x2,y2,’linetype2’);...

I Need only one command to customize graphic window ('title','xlabel', 'ylabel', 'axis', 'legend')

→ Specifying 'title', 'ylabel', 'xlabel', ... more than one timeoverwrites previous de�nition

Example

» x = -10:0.1:10;» y1 = eval_poly3(1:4,x);» y2 = eval_poly3([0,5,0,-20],x);» figure(1); % not necessary» plot(x,y1,’r’,x,y2,’b-.’)» legend(’y=xˆ3+2xˆ2+3x+4’,...’y=5xˆ2-20’)» xlabel(’x’)» ylabel(’y’)» title(’Two polynomials’);%another version in other window» figure(2);» hold on;» plot(x,y1,’r’)» plot(x,y2,’b-.’)% rest as above» hold off;

Contour plots

To get a �rst impression on 3-dimensional functions, we can usecontour plots:

De�nitionA curve in two dimensions on which the value of a function f (x , y)is a constant. Also known as equipotential curve.

contour(X,Y,Z,n) contour plot with n contour lines (default:n=5)

contour(X,Y,Z,v) contour plot with contour lines on thevalues of v (i.e. Z = vi )

contour3(X,Y,Z,n) 3D contour plot

Plotting lines

I Let x , y , z ∈ R3

I Similar to the previous section use:�plot3(x,y,z,’linetype’)�⇒ Plots a line through the points in 3D

» t = 0:pi/50:10*pi» plot3(sin(t), cos(t),t)» xlabel(’sin(t)’)» ylabel(’cos(t)’)» zlabel(’t’)

Plotting surfaces

SurfaceA surface is de�ned by a function f (x , y), i.e. we compute to everyvalue of (x , y) the �height� of the function by z = f (x , y).

In order to draw such a surface:I Choose a grid,

e.g. 2 ≤ x ≤ 4, 1 ≤ y ≤ 3⇒ [X,Y] =meshgrid(2:0.5:4,1:0.5:3);

I Compute f , e.g.f (x , y) = (x − 3)2 − (y − 2)2

⇒ Z = (X-3). 2̂-(Y-2). 2̂;

I Draw the (shaded) surface using�surf� ⇒ surf(X,Y,Z)

You can add description asbefore.

Plotting surfaces cont.

Other plotting commands are:

surfc(X,Y,Z) surface plot with additional contour ploton xy -plane

mesh(X,Y,Z) mesh plot of surfacemeshc(X,Y,Z) mesh plot with additional contour plot on

xy -planemeshz(X,Y,Z) curtain plot (i.e. reference plane around

the mesh)

You can change the colormap used by, e.g. �colormap hot�

Charts in MATLAB

Charts can be drawn in the same manner as in previous section:bar vertical bar chartbar3 vertical bar chart (3D)barh horizontal bar chartbarh3 horizontal bar chart (3D)pie pie chartpie3 pie chart (3D)stem plot of discrete datastem3 plot of discrete data (3D)stairs stairstep plothist histogram

Histogram

hist(y) uses 10 equally spaced containershist(y,n) For n being a scalar, uses n equally spaced

containershist(y,x) For x being a vector, uses the values of x as

centers of the containers[n,x]=hist(...) Returns the number of elements per container

in the vector n and the centers of thecontainers in the vector x

» marks = [1 2 3 2 3 2 12 3 1...2 3 4 5 5 2 3 4 5]» hist(marks, 1:5)» xlabel(’marks’);» ylabel(’quantity’);

Splitting graphics windows

I Each graphic window can be split up into an m × n array

I Cells are counted from 1 to mn row-wise

I Asymmetrical division also possible

I In each cell all plot commands can be used

» subplot(3,1,1)» plot(x, sin(x))» grid, ylabel(’sin(x)’)» axis([0,2*pi,-1.2,1,2])» subplot(3,1,2)» plot(x,cos(x),’r’)» grid, ylabel(’cos(x)’)» axis([0,2*pi,-1.2,1.2])» subplot(3,1,3)» plot(x,cos(x),’r’,...x,sin(x),’b’)» grid, ylabel(’cos(x)/sin(x)’)» axis([0,2*pi,-1.2,1.2])» xlabel(’x’)

Export of graphics

I Plot your graphic → File → Save as

Di�erent commands:

I hgexport(’h’,’filename’): Writes the �gure ’h’tothe �le ’filename’

I print: Sends the current �gure to the printer (many di�erentoptions → see ’help print’)

I printpreview: Opens a GUI that shows a scaled version ofthe current active �gure window as it will be printed and givesthe possibility to customize the print