Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften.

Slides:



Advertisements
Similar presentations
Introduction to Eclipse. Start Eclipse Click and then click Eclipse from the menu: Or open a shell and type eclipse after the prompt.
Advertisements

Lab # 03- SS Basic Graphic Commands. Lab Objectives: To understand M-files principle. To plot multiple plots on a single graph. To use different parameters.
Plotting Selim Aksoy Bilkent University Department of Computer Engineering
Introduction to Matlab 7
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.
Chapter 3: Editing and Debugging SAS Programs. Some useful tips of using Program Editor Add line number: In the Command Box, type num, enter. Save SAS.
The Web Warrior Guide to Web Design Technologies
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 19P. 1Winter Quarter MATLAB: Script and.
MA/CS375 Fall MA/CS 375 Fall 2002 Lecture 4.
Introduction to MATLAB Northeastern University: College of Computer and Information Science Co-op Preparation University (CPU) 10/27/2003.
Introduction to MATLAB Northeastern University: College of Computer and Information Science Co-op Preparation University (CPU) 10/27/2003.
MATLAB - Lecture 22A Two Dimensional Plots / Chapter 5 Topics Covered:
EGR106 Week 6 MATLAB FILES Two Dimensional Plots Multiple Plots
How to Debug VB .NET Code.
Vectors and Plotting Selim Aksoy Bilkent University Department of Computer Engineering
1 Introduction to MatLab MatLab stands for Matrix Laboratory. As the name suggests most of the programming operations have as input or output a matrix.
Introduction to MATLAB Northeastern University: College of Computer and Information Science Co-op Preparation University (CPU) 10/29/2003.
Lecture 9 Plotting in 2-D Plotting in 2-D, Plotting Multiple Curves, Plotting with Figures, Plot Settings, Scaling, Legends © 2007 Daniel Valentine. All.
An introduction to Plotting in MATLAB Rikard Johansson Department of Biomedical Engineering (IMT) Linköping University
Introduction to programming in MATLAB MATLAB can be thought of as an super-powerful graphing calculator Remember the TI-83 from calculus? With many more.
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
Chapter 5 Review: Plotting Introduction to MATLAB 7 Engineering 161.
PLOTS AND FIGURES DAVID COOPER SUMMER Plots One of the primary uses for MATLAB is to be able to create publication quality figures from you data.
ENG College of Engineering Engineering Education Innovation Center 1 2D Plots 1 in MATLAB Topics Covered: 1.Plotting basic 2-D plots The plot()
1 Workshop 4 (B): Visual Basic Test Project Mahidol University June 13, 2008 Paul Evenson University of Delaware Bartol Research Institute.
ELG 3120 Signal and System Analysis 1 Introduction to MATLAB TAs Wei Zhang Ozgur Ekici (Section A)(Section B) ELG 3120 Lab Tutorial 1.
Written by: Itzik Ben Shabat Technion - Israel Institute of Technology Faculty of Mechanical Engineering Laboratory for CAD & Lifecycle Engineering Lab.
1 Functions 1 Parameter, 1 Return-Value 1. The problem 2. Recall the layout 3. Create the definition 4. "Flow" of data 5. Testing 6. Projects 1 and 2.
Matlab Workshop 1/10/07 Lesson 1: Matlab as a graphing calculator.
COMP 116: Introduction to Scientific Programming Lecture 5: Plotting, Scripts and publishing.
Getting Started with MATLAB 1. Fundamentals of MATLAB 2. Different Windows of MATLAB 1.
CMPS 1371 Introduction to Computing for Engineers MatLab.
MAE 1202: AEROSPACE PRACTICUM An Introduction to MATLAB: Part 2 Mechanical and Aerospace Engineering Department Florida Institute of Technology Developed.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
Lecture 2 - Matlab Introduction CVEN 302 June 5, 2002.
Barbara/Pratik/Yu. Outline Matlab desktop M-files Variables Arrays Plots.
UW CSE 190p Section 7/26, Summer 2012 Dun-Yu Hsiao.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 5.1 Test-Driving the Inventory Application.
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,
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
Sept. 26, 2005 Lecture 6 - By Paul Lin 1 CPET 190 Lecture 6 Problem Solving with MATLAB
A simple classification problem Extract attributes Pattern Pattern recognition decision x C1 C2.
Introduction to Matlab Part II 1Daniel Baur / Introduction to Matlab Part II Daniel Baur / Michael Sokolov ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften.
EGR 115 Introduction to Computing for Engineers 2D Plotting – Part I Wednesday 17 Sept 2014 EGR 115 Introduction to Computing for Engineers.
Introduction to Matlab  Matlab is a software package for technical computation.  Matlab allows you to solve many numerical problems including - arrays.
Introduction to Engineering MATLAB – 9 Plotting - 2 Agenda Formatting plots.
JavaScript Introduction and Background. 2 Web languages Three formal languages HTML JavaScript CSS Three different tasks Document description Client-side.
Introduction to Programming on MATLAB Ecological Modeling Course Sep 11th, 2006.
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,
EEE 242 Computer Tools for Electrical Engineering
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.
Plotting ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne.
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.
Computer Application in Engineering Design
Ch3 Graphics Overview of Plotting Editing Plots
Course Information Do not rely on color to distinguish curves (due to black-white printout). Use different line styles to distinguish curves (solid, dashed,
Lecture 25: Exploring data
Scripts & Functions Scripts and functions are contained in .m-files
MATLAB How to use (using M-files) Double click this icon
MATLAB How to use (using M-files) Double click this icon
MATLAB How to use (using M-files)
Introduction to MATLAB Plotting LAB 3
Yang-Ming University, Taipei, Taiwan
Plotting Signals in MATLAB
Presentation transcript:

Introduction to Matlab 7 Part III 1Daniel Baur / Introduction to Matlab Part III Daniel Baur ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften ETH Hönggerberg / HCI F128 – Zürich

Review of program control  Decisions  Error handling  try... catch err statements; end  Loops  break;  continue; 2Daniel Baur / Introduction to Matlab Part III

Data type «struct» 3Daniel Baur / Introduction to Matlab Part II comp(1).name = 'water'.MW = density= 1.Antoine= [8.07; 1730; 233]; comp(2).name = 'ethanol'.MW = density= Antoine= [8.20; 1643; 230]; comp(3).name =....MW =....density=....Antoine=... comp(1,n)struct

Review of m-files  What is an m-file?  An m-file is a collection of commands. It is equivalent to programs, functions, subroutines, modules, etc. in other programming languages. It can even contain entire class definitions.  An m-file can be used for  Creating a permanent record of what you are doing  Experimenting on an algorithm  Writing utilities and whole programs  Types of m-files  Script m-file: No input and output. Operates on workspace variables.  Function m-file: Start with the function key-word, accepts inputs and gives outputs. All variables are local.  Class m-file: Contains the classdef key-word, used in object oriented programming. 4Daniel Baur / Introduction to Matlab Part II

Example of a script (mysum.m)  The script reads  How to run the script?  From the command window (check the path!)  From the editor (press Run button or use Debug  Run or press F5) 5Daniel Baur / Introduction to Matlab Part II

How to deal with error messages in matlab  The topmost error message is usually the one containing the most useful information  The underlined parts of the message are actually links that you can click to get to the line where the error happened! 6Daniel Baur / Introduction to Matlab Part III

Orange = Unusual Syntax The script / function will run, but there are some unusual or subobtimal commands This can be caused by (for example): Not preallocating variables, using variables in an unusual way, overriding variables before they are used even once, etc. Clicking the square and mouse-over works too Orange = Unusual Syntax The script / function will run, but there are some unusual or subobtimal commands This can be caused by (for example): Not preallocating variables, using variables in an unusual way, overriding variables before they are used even once, etc. Clicking the square and mouse-over works too Red = Syntax Error The script / function will produce and error when run. Click the red square to jump to the error, mouse over the red bar or the underlined part to get some info Red = Syntax Error The script / function will produce and error when run. Click the red square to jump to the error, mouse over the red bar or the underlined part to get some info Preventing errors before they happen  The MATLAB editor does (some) on-the-fly proof reading 7Daniel Baur / Introduction to Matlab Part III Green = OK No syntax errors or unusual syntax found Be aware that of course there can still be semantical errors! Green = OK No syntax errors or unusual syntax found Be aware that of course there can still be semantical errors!

Functions in Matlab 8Daniel Baur / Introduction to Matlab Part III Function name (= file name) Outputs Inputs Function description (spend a minute or two here to save yourself hours later on) Function body (where the magic happens) function function keyword

Example of a Function  Calling the function 9Daniel Baur / Introduction to Matlab Part III

Exercise 1.Create a function called «myFirstFunction.m»  Scope:Compute f(x) = 2*x^2 – exp(x) + 3  Inputs:Value of x where f(x) is computed Outputs:f(x) at x 2.Run the function for different values of x y 3.Evaluate the function at 40 points evenly spaced from -5 to +5 and save the values in y yxplot(x,y) 4.Plot y vs. x, use plot(x,y) 10Daniel Baur / Introduction to Matlab Part III

Local vs. global variables  All variables in functions are local variables  This means they exist only inside the function and are cleared from the workspace after the function ends global  You can create variables that are seen everywhere by using the global key-word 11Daniel Baur / Introduction to Matlab Part III ALPHA has changed everywhere!

Local vs. global variables (Continued)  It is common practice to name global variables in CAPS  Try to avoid global variables, since they tend to make your code confusing and hard to understand  If you want to pass a lot of variables to a lot of functions, use structs and parametrizing functions 12Daniel Baur / Introduction to Matlab Part III

Local vs. global variables (Continued) persistent  If you want to create a variable that keeps its value from one function call to the next (for example an evaluation counter), use the persistent key-word 13Daniel Baur / Introduction to Matlab Part III Persistent variables are local variables spanning all calls of a specific function.

Solving problems / exercises in Matlab  Usually when you solve problems in Matlab, your program folder will look something like this: 14Daniel Baur / Introduction to Matlab Part IV Main executable (script m-file) Functions used by main.m

The main File  There is usually one main file that is executed, or one per task  It defines or loads variables, operates on them (calculations, solver calls, restructuring, etc.) and displays or saves the results 15Daniel Baur / Introduction to Matlab Part IV

Calling functions from scripts  Scripted program execution is like riding a train down the main file: 16Daniel Baur / Introduction to Matlab Part III

Debugging functions in Matlab keyboard  The command keyboard interrupts program execution and brings up the command prompt  You can use this prompt normally, for things like looking at variables or even changing them return  The command return continues program execution (with the changed variables!) dbquit  Use the command dbquit (DeBugQuit) or the toolbar to terminate program execution immediately keyboard dbquit  Note that when keyboard is in a loop, it will stop at every iteration; dbquit is the quickest way to escape here keyboard catch  A very powerful debugging option is to use keyboard in a catch block (interrupt if an error occurs!) 17Daniel Baur / Introduction to Matlab Part III

Debugging example 18Daniel Baur / Introduction to Matlab Part III «Keyboard» command prompt Program execution has been halted here

Recursive functions  Functions in Matlab can be called recursively  Example: Compute the factorial of an integer number  There is an adjustable limit of 500 recursive calls, after which an error is thrown to prevent stack overflow 19Daniel Baur / Introduction to Matlab Part III

Exercise 1.Plot the result of «myFirstFunction» vs. [-5:0.5:5] hold on 2.Type hold on ; This prevents plot overwriting plot(x, f, 'ro') 3.Plot the result of «myFirstFunction» vs. [-5:0.5:5] using the command plot(x, f, 'ro') axis 4.Check the current axis interval with axis axis([ ]) 5.Define a new interval with axis([ ]) xlabel('x')ylabel('f(x)') 6.Set axis labels by xlabel('x'), ylabel('f(x)') plot(x, 3*sin(x)) 7.Superimpose plot(x, 3*sin(x)) figure 8.Create a new figure with figure semilogy 9.Plot the function 2*exp(x 2 +1)+6 using semilogy 10.Place axis labels and rescale the plot to x= and y = Daniel Baur / Introduction to Matlab Part III

More on 2D Plots  Try:  x = linspace(0,10,100); y = tanh(x).*cos(x);  plot(x,y)  You can change color, line style, marker style, line width and more:  plot(x, y, 'rx--', 'LineWidth', 2)  Plotting multiple data sets:  plot(x1, y1, x2, y2)  plot(x1, y1); hold on plot(x2, y2); hold off 21Daniel Baur / Introduction to Matlab Part III Color Marker Line Style Line Width (default: 0.5)

Line color and style specifiers Line ColorSpecifier Red 'r' Green 'g' Blue 'b' Cyan 'c' Magenta 'm' Yellow 'y' White 'w' Black 'k' Line StyleSpecifier Continuous (default) 'r' Dotted Line ':' Dashed Line '--' Dash-dotted Line '-.' 22Daniel Baur / Introduction to Matlab Part III

Marker style specifiers Marker StyleSpecifier Plus Sign '+' Circle 'o' Asterisk '*' Point '.' Cross 'x' Square 's' Diamond 'd' Five-pointed Star 'p' Six-pointed Star 'h' Marker StyleSpecifier Triangle (up) '^' Triangle (down) 'v' Triangle (left) '<' Triangle (right) '>' 23Daniel Baur / Introduction to Matlab Part III doc lineseriesproperties Much more on line properties: doc lineseriesproperties

Annotating graphs  You can use these commands to add descriptive elements to your graphs  text(x, y, 'I''m a text');  title('Sub_{script}'); xlabel('I''m a label'); ylabel('Results');  legend('Data1', 'Data2', 'Location', 'Best')  Most Matlab annotators can interpret LaTeX-Commands! 24Daniel Baur / Introduction to Matlab Part III

Text properties Property NameDescriptionProperty Value RotationText orientationScalar (deg.), default: 0 FontAngleNormal, ItalicDefault: Normal FontNameSpecifies fontArial, Times, Courier, etc. FontSizeSize of the fontScalar, default: 10 FontWeightThickness of the fontLight, normal, bold ColorText ColorSame as for line BackgroundColorColor of backgroundSame as for line EdgeColorColor of box around textSame as for line LineWidthLine width of the box lineScalar, default: Daniel Baur / Introduction to Matlab Part III

Other types of plots  Plot a function in an interval  + cos(x.^2), [1,10]);  [x,y] = + cos(x.^2), [1,10];  [x,y] = + cos(x.^2), [1,10]; No plot!  Different scales on the axes  semilogx(x,y)  semilogy(x,y)  loglog(x,y)  Different coordinate systems  theta = linspace(0, 2*pi); r = 1./(1+theta.^2); polar(theta, r); 26Daniel Baur / Introduction to Matlab Part III θ r

Plots with error bars  x = linspace(1,10);  y = 10./x;  er = randn(size(y));  errorbar(x, y, er);  The errorbars go from y-er to y+er 27Daniel Baur / Introduction to Matlab Part III

3D plots I: Lines in space  t = linspace(0, 2*pi);  x = sqrt(t).*cos(2*t);  y = sqrt(t).*sin(2*t);  z = t;  plot3(x,y,z)  grid on 28Daniel Baur / Introduction to Matlab Part III The same line style options apply here. grid on also works for other plots.

3D plots II: Surfaces  x = linspace(-5, 5, 30);  y = linspace(-2, 2, 20);  [X, Y] = meshgrid(x,y);  Z = sin(X).* cos(Y);  mesh(X,Y,Z);  surf(X,Y,Z);  shading interp;  contour(X,Y,Z);  colorbar; 29Daniel Baur / Introduction to Matlab Part III