Dan Witzner Hansen  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector.

Slides:



Advertisements
Similar presentations
Lecture 5.
Advertisements

CSE 123 Plots in MATLAB. Easiest way to plot Syntax: ezplot(fun) ezplot(fun,[min,max]) ezplot(fun2) ezplot(fun2,[xmin,xmax,ymin,ymax]) ezplot(fun) plots.
Plotting Selim Aksoy Bilkent University Department of Computer Engineering
Introduction to Matlab
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.
Introduction to MATLAB for Biomedical Engineering BME 1008 Introduction to Biomedical Engineering FIU, Spring 2015 Lesson 2: Element-wise vs. matrix operations.
MATLAB – What is it? Computing environment / programming language Tool for manipulating matrices Many applications, you just need to get some numbers in.
MATLAB - Basics Centro de Informática Universidade Federal de Pernambuco Aprendizagem de Máquina – IN1102 Arley Ristar –
MATLAB - Lecture 22A Two Dimensional Plots / Chapter 5 Topics Covered:
Introduction to Matlab Tutorial for CS4MN3/SE3X03 Wen Yu McMaster University.
An Introduction to MATLAB Magali Billen U C Davis, Geology Department.
MATLAB Week 3 17 November Outline Graphics – Basic plotting – Editing plots from GUI – Editing plots from m-file – Advanced plotting commands.
Introduction to Matlab 332:202 Discrete Mathematics Spring 2007.
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Matlab intro The Environment
EPSII 59:006 Spring Outline Managing Your Session File Usage  Saving Workspace  Loading Data Files  Creating M-files More on Matrices Review.
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.
Martin Ellison University of Warwick and CEPR Bank of England, December 2005 Introduction to MATLAB.
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,
CMPS 1371 Introduction to Computing for Engineers PLOTTING.
Introduction to MATLAB
MATLAB Plotting With MATLAB 1. Two Dimensional Plots The xy plot is the most commonly used plot by engineers The independent variable is usually called.
ELG 3120 Signal and System Analysis 1 Introduction to MATLAB TAs Wei Zhang Ozgur Ekici (Section A)(Section B) ELG 3120 Lab Tutorial 1.
How to Use MATLAB A Brief Introduction. 2 What can MATLAB do? Matrix Operations Symbolic Computations Simulations Programming 2D/3D Visualization.
MEGN 536 – Computational Biomechanics MATLAB: Getting Started Prof. Anthony J. Petrella Computational Biomechanics Group.
ECE 1304 Introduction to Electrical and Computer Engineering Section 1.1 Introduction to MATLAB.
A Brief Introduction to Matlab Laila Guessous Dept. of Mechanical Engineering Oakland University.
INTRODUCTION TO MATLAB LAB# 01
Matlab Programming for Engineers Dr. Bashir NOURI Introduction to Matlab Matlab Basics Branching Statements Loops User Defined Functions Additional Data.
The Hong Kong Polytechnic University Industrial Centre 1 MatLAB Lesson 4 : Polynomial Edward Cheung Room W311g 2008.
Master in Optical Fiber Communications and Photonic Technologies Foundations of Digital Transmission - Fall quarter Introduction to Matlab.
1 DKT 211 Basic Communication Engineering LAB # 1A : (Lecture 1) Introduction to Matlab  Basic Features  Scientific features  Array Operations  Script.
Introduction to MATLAB Session 5 Simopekka Vänskä, THL 2010.
Matlab Screen  Command Window  type commands  Current Directory  View folders and m-files  Workspace  View program variables  Double click on a.
Numerical Analysis 3D Plots. A numerical method is a technique for computing a numerical approximation of the solution to a mathematical problem.
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 DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
1 Lecture 5 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
GRAPHICS AND VISUALISATION WITH MATLAB UNIVERSITY OF SHEFFIELD CiCS DEPARTMENT Deniz Savas & Mike Griffiths May 2015.
1 Faculty Name Prof. A. A. Saati. 2 MATLAB Fundamentals 3 1.Reading home works ( Applied Numerical Methods )  CHAPTER 2: MATLAB Fundamentals (p.24)
Introduction to Engineering MATLAB – 9 Plotting - 2 Agenda Formatting plots.
MATLAB ® for Engineers, Holly Moore Fourth Edition, Global Edition © Pearson Education Limited 2015 All rights reserved. Figure 5.1 Simple Plot of Time.
CS100A, Fall 1998, Lecture 201 CS100A, Fall 1998 Lecture 20, Tuesday Nov 10 More Matlab Concepts: plotting (cont.) 2-D arrays Control structures: while,
An Introduction to Programming in Matlab Emily Blumenthal
MATLAB (Matrix Algebra laboratory), distributed by The MathWorks, is a technical computing environment for high performance numeric computation and.
1-2 What is the Matlab environment? How can you create vectors ? What does the colon : operator do? How does the use of the built-in linspace function.
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.
Session III Plotting in MATLAB Rajeev Madazhy Dept of Mechanical Engineering LSU MATLAB Tutorials.
3D-Graphs A 3D surface is defined as: z = f(x, y)
Ch3 Graphics Overview of Plotting Editing Plots
MatLab – Palm Chapter 5 2-D & 3-D Plots
MATLAB DENC 2533 ECADD LAB 9.
MATLAB How to use (using M-files) Double click this icon
MATLAB How to use (using M-files) Double click this icon
MatLab – 2D Plots 2 MATLAB has many built-in functions and commands to create various types of plots. Instructor notes: We start with an example of some.
MATLAB How to use (using M-files)
Plotting Signals in MATLAB
An Introduction to MATLAB
Announcements P3 due today
How to Use MATLAB A Brief Introduction.
Introduction to Matlab
Presentation transcript:

Dan Witzner Hansen

 Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector and matrix manipulation  Lots of built in functions and code libraries  Implicit loops for arrays  Many preexisting functions  Filtering, converting, sorting, finding, means, minimum.  Lots of online material

 Avoid using too many libraries (and convert between formats)  Easy to see the connection between code and mathematics (Matrix of doubles is the primitive type)  Good plotting facilities (also for other courses)  Programming is a little different from what you have tried before – in some sense a little more primitive :D

 It has many applications in many diverse fields. (computer graphics, chemistry, biology, differential equations, economics, business,...)  It strikes a nice balance between computation and theory.  Essential the course

A matrix is a set of elements, organized into rows and columns rows columns

Patient Gender,age,height, weight

Column vector (default): Row vector:

 Addition:  Multiplication with scalar  Multiplication :  Inner product (“row times column”)  Outer product (“column times row”) v w V+w vav

>> a = 5; >> b = [ ]; >> c = [1:0.25:2]’ c = >> c(5) = -10 c = >> a*b >> c = [ ] >> a-b ans = [ ]

>> x = [2 -5]; >> norm(x) ans = Norm: Orthogonal: Orthonormal: Orthogonal and ||x||=||y||=1

 Addition, Subtraction, Multiplication

+ - addition, subtraction / ^ matrix multiplication, division, power * [ 2 x 3] * [3 x 2] = [2 x 2] [ ] define matrix.*./.^ array multiplication, division, power (arrays must be the same size) n’ transpose, complex conjugate ; separate rows, non-echo end of line.

>> c = [1 2 3; 4 5 6; 7 8 9] c =

zeros(n,m) an n x m matrix of zeros ones(n,m) an n x m matrix of ones rand(n,m) an n x m matrix of uniformly distributed numbers randn(n,m) an n x m matrix of normally distributed numbers

>> c = [1 2 3; 4 5 6; 7 8 9]; >> d = [1 1 1; 2 2 2; 3 3 3]; Res = c*d’; M = c.*d; Add = c+d;

: “all elements” of row, column or between 2 numbers. ( ) specify elements of a defined vector/matrix / A/B = (B'\A')'B'\A ^z = x^y, x or y must be a scalar. X = A\B is the solution to the equation A*X = B (more about this next week)

>> A = zeros (5,5) >> c = [ ] >> A[1,:] = c; >> diag([ ]) >> eye(3)

>> d = c(1:2,2:3) d = >> e = [d d] e = >> f = [d; d] f = Extracting part of a matrix ( ) specify elements of an array, separates dimension : entire row or column Combining Arrays Horizontal concatenation no punctuation vertical concatenation ; separates arrays Vectors of indices

>> x = [ ]; >> minx = min(x) minx = 0 >> y = sort(x) y = >> find(x) ans = >> i4 = find(x==4) i4 = 6 Functions for extracting data: min, max, mean, median, sort find

>> c = [1 2 3; 4 5 6; 7 8 9; ; 3 3 3; 4 4 4]’ c = >> size (c) 3 6 >> d = reshape(c, 3,3,2) d(:,:,1) = d(:,:,2) = >> size(d) ans = 3 3 2

>> a = [ ]; >> b = a; >> >> c = a.*b c = >> d = a*b’ d = 55 Array operations include an implicit loop through the entire array. The operation is repeated for each element in the array. The matrix operation does the linear algebra operation for the matrices.

pi i,j sqrt(-1) imaginary unit eps e-016 (small number, can also be set to a number) inf infinity (from 1/0) nan not-a-number (from 0/0)

 Commands can be entered one at a time on the command line within MATLAB  A series of commands (functions) can be entered into a dot-M file (name.m).  To run the set of command, just type the name of the dot-M file:  dot-M file namet.m  execute commands >> name [a,b,c,d] = someFunction(x,y,z);

>>[A,B]= example1('Example 1',0.1,0,5,0.2,0,5); >> help example1 % example1.m % Comment lines start with the percent sign % This is an example function which takes 3 parameters modelname is a string with the % name of the model to be used in the title line. dx and dy are the intervals for the % x and y variables, which range in value from from xmin to xmax or ymin to ymax. function [Value1,Value2]=example1(modelname,dx,xmin,xmax,dy,ymin,ymax); % Define x and y x = [xmin:dx:xmax]; y = [ymin:dy:ymax]; % Make a mesh out of x and y

 MATLAB is case sensitive:  a and A are different.  Use a ; at the end of the line to stop commands from echoing to the screen  Use   keys to scroll through previously entered commands and rerun.  Help / helpwin will tell you how to use a function and what it does. (e.g. >> help plot or >>help ops ). Help on toolbar

n = 5 for i = 1:n a(i) = i + 2; end test = 1; cnt = 1; while (test ~= 0) b(cnt) = 1/test; test = test - 0.1; cnt = cnt + 1; end For Loop default increments by 1 can define other increment for i = 1:0.1:n While Loop continues as long as boolean expression is true.

if a == 0 b = a; else b = 1/a; end if and(x > xmin,x < xmax) disp(‘x is within limits’); elseif (x > xmax) disp(‘x is too large’); elseif (x < xmin) disp(‘x is too small’); end If - elseif - else can have several sequential boolean tests can use both else and elseif or just one.

 save  creates matlab.mat with all variables in workspace  save fname  creates fname.mat with all variables  save fname var1 var2  saves only variables var1 & var2  save fname.txt var1 -ascii -tabs -double  saves var1 as a table of ASCII numbers called fname.txt

load file of ascii data in columns >> load filename data loaded into variable filename >> A = load(‘filename’); data loaded into variable A fscanf formatted ascii data fread binary data file fopen open files (for fscanf, fread ) fclose closes files

figure subplot title Xlabel,ylabel Zlabel text axis colorbar shading set gca gcf creates a new figure window defines multiple plots on a single page defines plot title text X,y,x axes label text puts text at specified coordinates defines the axis limits creates a colorbar defines type of shading (faceted, flat, interp) use to define properties of the axis or figure returns handle to current plot axis returns handle to current figure

Plot loglog semilogx semilogy bar errorbar fplot hist polar rose stairs linear plot of lines, points or symbols log-log scale plot log (x-axis) - linear (y-axis) plot log (y-axis) - linear (x-axis) plot Linear plot with error bars Function plot histogram polar coordinate plot angular histogram plot stairstep plot

plot3 fill3 contour,contour3 pcolor quiver, quiver3 stream, stream3 mesh, meshc, meshz surf, surfc, surfl surfnorm cylinder, sphere Plot lines and points in 3D space Filled 3D polygons in 3D space contour data in 2D or 3D space checkerboard color plot in 2D vector plot in 2D or 3D Stream lines in 2D or 3D Mesh surface in 3D, with contours or zero plane. Shaded surface in 3D Display surface normal vectors. Generate a cylinder or sphere.

Cosine Curve

>> example1('Example 1',0.1,0,5,0.2,0,5); >> help example1 % example1.m % Comment lines start with the percent sign % This is an example function which takes 3 parameters modelname is a string with the % name of the model to be used in the title line. dx and dy are the intervals for the % x and y variables, which range in value from from xmin to xmax or ymin to ymax. function example1(modelname,dx,xmin,xmax,dy,ymin,ymax); % Define x and y x = [xmin:dx:xmax]; y = [ymin:dy:ymax]; % Make a mesh out of x and y [X,Y] = meshgrid(x,y); % takes vectors and repeats x for every y and y for every x. % Define a function for every x, y pair Z = sin(X).*cos(Y); whos X Y Z

minz = min(min(Z)); maxz = max(max(Z)); save ex1dat X Y Z % saves variables in binary matlab format % Plotting figure; % opens a new figure window. subplot(2,3,1) % 6 plots in figure split into 2 rows and columns % 1- first plot is in top-left plot(X(1,:),Z(1,:),'r') % plot all the points in the % first column as a red line % (also b, g, y, c, m, k, w). title(['Plot 1: ' modelname]); xlabel('X'); ylabel('Z'); grid;% Plots grid lines axis([xmin-dx xmax+dx minz maxz]);

subplot(2,3,2) plot(Y(:,2),Z(:,2),'gx'); % plots points as green x's % (type 'help plot' for full list). vlab = input(‘Enter label: ‘,’s’); % get data from command line hold on; % allows you to overlay more % symbols, lines etc... plot(Y(:,4),Z(:,4),'ro'); plot(Y(:,6),Z(:,6),'m*'); title('Plot 2: plot symbols'); text(2,0.5,vlab);% add text labels xlabel('Y'); ylabel('Z'); grid; axis([ymin-dy ymax+dy minz maxz]); subplot(2,3,3) plot(Y,Z,'.-'); % plot all rows of X versus all rows of Z % -- dashed line, also -solid, : dotted, -.dash-dot % can also combine symbols and line 'o-; title('Plot 3: whole array'); xlabel('Y'); ylabel('Z'); grid; axis([ymin-2*dy ymax+2*dy 2*minz 2*maxz]);

subplot(2,3,4) pcolor(X,Y,Z); shading flat; colorbar('horiz'); title('Plot 4: pcolor'); xlabel('X'); ylabel('Y'); subplot(2,3,5) meshc(X,Y,Z); shading flat; colorbar('horiz'); title('Plot 5: meshc'); xlabel('X'); ylabel('Y'); zlabel('Z') subplot(2,3,6) surfl(X,Y,Z); shading interp; colorbar; set(gca,'Zlim',[-2 2]); view(15,20); title('Plot 6: surfl'); xlabel('X'); ylabel('Y'); zlabel('Z')

% Save data to ascii file as column data [nx,ny] = size(X); X = reshape(X,nx*ny,1); Y = reshape(Y,nx*ny,1); Z = reshape(Z,nx*ny,1); dat = [X Y Z]; keyboard; save ex1.asc dat -ascii Cosine Curve

figure(1) ; clf t = linspace(0, 2*pi, 512) ; [u,v] = meshgrid(t) ; a = -0.2 ; b =.5 ; c =.1 ; n = 2 ; x = (a*(1-v/(2*pi)).* (1+cos(u)) + c).* cos(n*v) ; y = (a*(1-v/(2*pi)).* (1+cos(u)) + c).* sin(n*v) ; z = b*v/(2*pi) + a*(1-v/(2*pi)).* sin(u) ; surf(x,y,z,y) shading interp axis off axis equal colormap(hsv(1024)) material shiny lighting gouraud lightangle(80, -40) lightangle(-90, 60) view([ ])

wholists all or specified variables currently defined whossame as who, but also gives dimensions of arrays, size in bytes and type (e.g. double, complex) clearclears all or specified variable from memory keyboardwithin a dot-M file gives command control to the keyboard. Type return to continue. ginput(N)Get N mouse clicks

 Reading and saving images easy (imread, imshow)  Often want to draw on top of an image  Hold (on/off) >> I = imread(‘GroundFloor.bmp’) >> figure(1) >> imshow(I); >> [X,Y,Z] = ginput(2) >> hold on >> plot(X,Y,’rx’,’MarkerSize’,10,’LineWidth’,3) >> hold off

 Remember the help / helpwin commands  MATLAB help pages:  describe how to use functions and gives examples  provides theory behind more complex functions  Getting Started  MATLAB Functions Listed by Category  MATLAB Functions Listed Alphabetically  MATLAB Reference Guide, User’s Guide  same as help pages, but in print -- sometimes nice to flip through when you’re not sure what you’re looking for

 Try to get Matlab running  Take a look at a Matlab primer  Watch some movies – if you have not done so already  Next week:  More linear algebra  DON’T LET THAT DISCURAGE YOU

Feel free to me at any time