WELCOME EF 105 Fall 2006 Week 10. Topics: 1. Engineering Problem Solving 2.Programming Logic 3.Intro to MATLAB.

Slides:



Advertisements
Similar presentations
Introduction to Matlab
Advertisements

Programming in Visual Basic
 2005 Pearson Education, Inc. All rights reserved Introduction.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
CMT Programming Software Applications
EGR 106 – Week 2 – Arrays Definition, size, and terminology Construction methods Addressing and sub-arrays Some useful functions for arrays Character arrays.
EGR 106 – Week 2 – Arrays & Scripts Brief review of last week Arrays: – Concept – Construction – Addressing Scripts and the editor Audio arrays Textbook.
Introduction to MATLAB
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.
Introduction to MATLAB ENGR 1187 MATLAB 1. Programming In The Real World Programming is a powerful tool for solving problems in every day industry settings.
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.
1 MATLAB 基礎. 2 MATLAB  Workspace: environment (address space) where all variables reside  After carrying out a calculation, MATLAB assigns the result.
January 24, 2005 Lecture 3 - By P. Lin 1 CPET 190 Lecture 3 Problem Solving with MATLAB
Chapter 4 MATLAB Programming Combining Loops and Logic Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Lecture 1: Introduction Lecture series based on the text: Essential MATLAB for Engineers and Scientists By Hahn & Valentine
INTRO TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files.
MATLAB INTRO CONTROL LAB1  The Environment  The command prompt Getting Help : e.g help sin, lookfor cos Variables Vectors, Matrices, and Linear Algebra.
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
1 Chapter 1 MATLAB Primer This introductory chapter is relatively short and has as its main objective the introduction of MATLAB ® to the reader. This.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Objectives Understand what MATLAB is and why it is widely used in engineering and science Start the MATLAB program and solve simple problems in the command.
1 Lab of COMP 406 Teaching Assistant: Pei-Yuan Zhou Contact: Lab 1: 12 Sep., 2014 Introduction of Matlab (I)
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.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
INTRODUCTION TO MATLAB LAB# 01
What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation tools. Others include Maple Mathematica MathCad.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Introduction to Matlab Module #2 Page 1 Introduction to Matlab Module #2 – Arrays Topics 1.Numeric arrays (creation, addressing, sizes) 2.Element-by-Element.
Getting Started with MATLAB 1. Fundamentals of MATLAB 2. Different Windows of MATLAB 1.
CMPS 1371 Introduction to Computing for Engineers MatLab.
10/24/20151 Chapter 2 Review: MATLAB Environment Introduction to MATLAB 7 Engineering 161.
Introduction to Programming with RAPTOR
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
>> x = [ ]; y = 2*x y = Arrays x and y are one dimensional arrays called vectors. In MATLAB all variables are arrays. They allow functions.
CSE123 Lecture 3 Files and File ManagementScripts.
Lecture 20: Choosing the Right Tool for the Job. What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
A simple classification problem Extract attributes Pattern Pattern recognition decision x C1 C2.
Introduction to Matlab  Matlab is a software package for technical computation.  Matlab allows you to solve many numerical problems including - arrays.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Digital Image Processing Introduction to M-function Programming.
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
Structured Programming II: If Statements By the end of this class you should be able to: implement branching in a program describe and use an “if” statement.
INTRODUCTION TO MATLAB Dr. Hugh Blanton ENTC 4347.
Introduction to Engineering MATLAB – 4 Arrays Agenda Creating arrays of numbers  Vectors: 1-D Arrays  Arrays: 2-D Arrays Array Addressing Strings & String.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
Matlab for Engineers Matlab Environment Chapter 2.
NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS ( NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS (PRACTICAL PART) Tutorial 2 : Matlab - Getting Started.
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
Manipulating MATLAB Vector, Matrices 1. Variables and Arrays What are variables? You name the variables (as the programmer) and assign them numerical.
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 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
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.
ECE 1304 Introduction to Electrical and Computer Engineering
Matlab Training Session 4: Control, Flow and Functions
MATLAB DENC 2533 ECADD LAB 9.
Introduction to C++ Programming
Use of Mathematics using Technology (Maltlab)
T. Jumana Abu Shmais – AOU - Riyadh
Presentation transcript:

WELCOME EF 105 Fall 2006 Week 10

Topics: 1. Engineering Problem Solving 2.Programming Logic 3.Intro to MATLAB

Engineering Problem Solving Define the problem clearly Work hand examples Develop the Algorithm (Steps to follow) Document the Algorithm with a FLOWCHART Implement the Algorithm (Write computer program) Test the Implementation (Run the Program) Evaluate the Results

PROGRAMMING LOGIC: Top-Down Algorithm Development Divide and Conquer Break Problem into smaller tasks. Define the interaction between tasks. Recursively solve the individual tasks. Build up the overall solution from the pieces.

Structured Programming Combination of –Sequences –Selections –Loops Sequences Series of operations that are performed in order. Selections Choose one path from two or more possible paths. Loops Execute a block of code repeatedly as long as some condition is met.

Basic Flowcharting Elements test? F T start task I/O task stop Selection Block Arrows show the flow - cannot diverge but can converge. Exit Point Execution Block Input/Output Block Entry Point

Selection Statements Selectively choose one path of execution. –Based on the evaluation of a test. –Logical Test outcome is either TRUE or FALSE. test? if_codeif()T F test? if_codeelse_code if()...else F T

Loop Structures Special case of Selection Statement One branch eventually leads back to the original selection statement. Permits a block of code to be executed repeatedly as long as some test condition is satisfied. loop_cod e test? F T inc_code ini_co de next_cod e

Basic Flowchart Symbols Entry Exit TaskI/OQ? T F

Practice: Algorithm and Flowchart Compute a sum of all integers from 1 to 100 and displays the result Step 1: Understand the problem: Computes a sum of all integers from 1 to 100 Step 2: What is the input? Step 3: What is the output? Start from 1, stop if reach 100 or (1 and 100) Sum

Algorithm Step 4: How do we compute the output? (first solution) Step 4.1: Start with the current integer: 1 Step 4.3: Add the current integer to Sum Step 4.2: Sum starts with 0 Step 4.4: If the current integer is less than 100, keep on adding the current integer to sum and increase It by 1(i.e, go back to 4.3). Step 4.5:Otherwise, print out the sum

Flowchart Step 4.3: Add the current integer to Sum Step 4.1: Start with the first integer: 1 Step 4.2: Sum starts with 0 Step 4.4: If the current integer is less than 100, go to next integer and keep on adding the current integer to sum (i.e, go back to 4.3). Step 4.5:Otherwise, print out the sum Stop Current Integer=1 Sum=0 Sum = Sum + Current Integer < 100 Increase Current Integer by 1 Print Sum Start

Intro to Matlab Inside Matlab This is what you should see once Matlab has loaded. The three most useful areas in the Matlab window are: 1. Right ‘command’ window is used for inputting commands 2. Top left ‘workspace’ window notes size of matrices used 3. Bottom left ‘command history’ window maintains a sequential list of past commands. Command History Workspace Command Window Command History Command Window Command Window

Help in MATLAB The following are three ways to access Matlab’s help files: 1. a. From options at top of Matlab window select Help  Matlab Help b. Select ‘Index’ tab c. Type topic to be searched in box 2. In Matlab window type a command preceded by ‘help’ or 'doc' For example,the following commands would produce a help file for the ‘plot’ command. >> help plot or >>doc plot 3. a. Double click command for which you want help b. Right-click on command c. Select ‘Help on Selection’

Creating files in MATLAB A. To create a new ‘M-file’ do one of the following: 1. In top left corner of Matlab window select File  New  M-file 2. Select ‘New M-file’ shortcut button located at the top left corner of Matlab screen B. Typing the following clears the command window: >> clc C. Typing a semicolon at the end of a command suppresses output. Note the difference between typing the following commands: >> x=0:0.5:10 >> x=0:0.5:10;

How/Where to write program Go to MATLAB command window File-New-M-File M-file is an Editor window Write your program in M-file Save in temp/ or your Disk. In command window, Run this file.

+ addition - subtraction * multiplication / right division ^ power Basic Operators

Review Arithmetic Operations and Precedence OperationAlgebraicMatlab FormScalar additiona + ba + b subtractiona – ba – b multiplicationa x ba * b divisiona ÷ ba / b exponentiation a b a ^ b PrecedenceOperation 1Parenthesis, innermost first. 2Exponentiation, left to right 3Multiplication & division, left to right 4Addition & subtraction, left to right

Use Parentheses to Override Operator Precedence Normal evaluation of expressions –Left-to-Right if same level and no parentheses e.g. 3^3-8/4+7-5*2 = = = = 22 Use parentheses to override e.g. (3^3-8)/4+(7-5)*2 = (9-8)/4+2*2 = 1/4+4 = 4.25

Overview of MatLab Variables Variables are names used to hold values that may change throughout the program. MatLab variables are created when they appear on the left of an equal sign. >> variable = expression creates the "variable'' and assigns to it the value of the expression on the right hand side. You do not need to define or declare a variable before it is used. >> x = 2 % creates a scalar The variable is x and % indicates a comment

Hands-On DEMO: Expression Evaluation In MatLab, enter the following: >> x = 1.4; >> numerator = x^3 - 2*x^2 + x - 6.3; >> denominator = x^ *x – 3.14; >> f = numerator / denominator

Variable Naming Naming Rules –must begin with a letter, cannot contain blank spaces –can contain any combination of letters, numbers and underscore (_) –must be unique in the first 31 characters MatLab is case sensitive: “name”, “Name” and “NAME” are considered different variables Never use a variable with the same name as a MatLab command (see next slide) Naming convention: –Usually use all_lowercase_letters –-or- camelNotation ("hump" in middle)

Reserved Words… MatLab has some special (reserved) words that you may not use as variable names: break case catch continue else elseif end for function global if otherwise persistent return switch try while

Commands involving variables –who: lists the names of defined variables –whos: lists the names and sizes of defined variables –what: l ists all your m-files stored in memory. –clear: clears all variables, reset the default values of special variables. –clear name: clears the variable named –clc: clears the command window –clf: clears the current figure and the graph window.

Scalars and Vectors and Matrices In MatLab, a scalar is a variable with one row and one column. A vector is a matrix with only one row OR only one column. The distinction between row and column vectors is crucial. When working with MatLab you will need to understand how to properly perform linear algebra using scalars, vectors and matrices. MatLab enforces rules on the use of each of these variables

Scalars Scalars are the simple variables that we use and manipulate in simple algebraic equations. To create a scalar you simply introduce it on the left hand side of an equal sign. –>> x = 1; –>> y = 2; –>> z = x + y;

Vectors A row vector in MATLAB can be created by an explicit list, starting with a left bracket, entering the values separated by spaces (or commas) and closing the vector with a right bracket. A column vector can be created the same way, and the rows are separated by semicolons. Example: >> x = [ *pi 0.5*pi 0.75*pi pi ] x = >> y = [ 0; 0.25*pi; 0.5*pi; 0.75*pi; pi ] y = x is a row vector. y is a column vector.

Simple Vector Commands x = start:end create row vector x starting with start, counting by one, ending at end x = start:increment:end create row vector x starting with start, counting by increment, ending at or before end linspace(start,end,number) create row vector x starting with start, ending at end, having number elements length(x) returns the length of vector x y = x' transpose of vector x (row to column, or columnn to row)

Hands-On DEMO: Creating Vectors >> a = 1:10 % leave off semi-colon to see what you get each time >> b = 0:0.1:1 >> c = [7 8 9] >> d = [10; 11; 12] >> length(b) >> linspace(0,100,21)

Hands-On DEMO: linspace function % Plotting a function using vector math x = linspace(0, 20, 100); % define 100 x values (from 0 to 20) y = 5*exp(-0.3*x).*sin(x); % compute y vector plot(x,y), xlabel('X'), ylabel('Y'), title('Vector calc') linspace( ) function can be very effective for creating the x vector…

A = [1 2 3; 4 5 6; 7 8 9] OR A = [ ] Must be enclosed in brackets Elements must be separated by commas or spaces Matrix rows must be separated by semicolons or a return Matlab is case sensitive Entering Matrices

x = [-1.3 sqrt(3) (1+2+3)*4/5]; –Output -> x = Matrix Manipulation: –x(5) = abs(x(1)); –Let r = [ ]; –xx = [x;r]; –z = xx(2,2); –T = xx(2,1:3); %row 2, col. 1-3 Semicolon at the end of a line means don’t print to the command window. Matrix Elements

Format short – Format short e –1.3333E E-006 Format long – Format long e – E E- 006 Format hex –3FF EB4B6231ABFD271 Defaults to format short. Output Format

Transpose: A = [1 2 3; 4 5 6; 7 8 9]; C = A’; D = [-1 0 2]’; Matrix Operations

The term array operations refer to element-by- element operations. Preceding an operator (*, /, ^, ‘) by a period indicates an element-by-element operation. The addition and subtraction, matrix and array operations are the same and don’t need a period before these operators. Example: –X = [1 2 3]; Y=[4 5 6]; –W = X.*Y; % to mult. X and Y arrays Array Operations(using the period)

Most often used for a time vector. time = 0.0:100.0; Time = 10.0:0.5:100.0; B_time = 100.0:-0.5:50.0; Variable = first:increment:last Generating Vectors

Empty Matrix E = []; EE([2 4],:) = []; –Empties rows 2 & 4 and all columns in rows 2 & 4. Zeros –Ze = zeros(2,3); –Creates a 2 x 3 matrix consisting all of zeros. Ones –O = ones(3,3); –Creates a 3 x 3 matrix consisting all of ones. Eye –I = eye(3,3); –Creates a 3 x 3 matrix consisting of an identity matrix. (I’s on diagonal and 0’s elsewhere) Useful Matrices

h = [1 2 3]; h' (nothing) ans = Switches from row to column vector. h * h' h.* h ans = 14 ans = * is matrix multiplication, and so the dimensions must line up correctly. (more on this later).* is entry-by-entry multiplication. Hands-On DEMO: Matrix Operations - Transposes Transpose – (indicated by `)new matrix created by exchanging rows and columns of original matrix

Hands-On DEMO: Functions of Vectors Most Matlab functions will work equally well with both scalars and arrays (of any dimension) >> A=[ ]; >> sin(A) ans = >> sqrt(A) ans =

Strings of Characters MatLab variables may also contain strings, which are vectors of individual characters. There is no typographical difference in appearance between numerical variables and string variables. The type of variable (numerical or string) is determined when the variable is created. –>> x = 5.2 % numeric –>> y = 'Chewbacca'% string

What are Character Strings? Arrays! Example: » C = 'Hello'; %C is a 1x5 character array. » D = 'Hello there'; %D is a 1x11 character array. » A = 43; %A is a 1x1 double array. » T = 'How about this character string?' » size(T) ans = 1 32 » whos % What do you observe? Name Size Bytes Class A 1x1 8 double array C 1x5 10 char array D 1x11 22 char array T 1x32 64 char array ans 1x2 16 double array Grand total is 51 elements using 120 bytes

Hands-On DEMO: Strings of Characters >> h = 'Hello'; >> w = 'World'; >> [h ', ' w] % called concatenation

format Examples ( MATLAB performs all computations in double precision) The format command described below switches among different display formats. Command Result Example format short 5 digit scaled fixed point format long 15 digit scaled fixed point format short e 5 digit floating-point e+00 format long e 15 digit floating-point e+00 format short g general purpose 5 or 1.25 or 3.0e-12 format bank Fixed dollars and cents 7.95 format rat Ratio of small integers 355/113 format compact Suppresses excess line feeds. format loose Add line feeds.

Hands-On DEMO: Formatting p=0:20; format short e % exponential [p' pow2(p)' pow2(-p)'] format short g % general purpose [p' pow2(p)' pow2(-p)']

In-Class Exercise : MatLab Calculations Do the following in MatLab –Create a matrix with the form: [2 3] [5 1] –Create a row (or "horizontal") vector of 2 elements, 3 and 4 (inclusive). –Create a second column (or 'vertical') vector with the elements 2 and 1 in that order. –Type 'whos' to view your variables. It should read (for example): –>> whos Name Size Elements Bytes Density Complex a 2 by Full No b 1 by Full No c 2 by Full No Grand total is 14 elements using 112 bytes Here, a is the matrix, b is the first vector, and c is the second vector. Now complete the following exercise: –Multiply your matrix by your first vector, above. –Perform element by element division of your resulting vector, divided by your second vector transposed. (The result should be a two element horizontal vector with 13 as each entry. ) –Type 'clear' to clear all variables from the workspace. Add your name as % comment, print Command Window and turn in

Saving/Loading Data Values Be sure you have the correct Current Directory set clear, clc –clear workspace and command window to start assign and calc a few values save file_name –saves file_name.mat in current directory –saves all defined variables clear; load file_name –brings workspace back

Hands-On DEMO: Saving Workspace First make sure your workspace is clear, and that your Current Directory is set to "My Documents" subfolder with your username (e.g. Djackson) Create a few scalars and vectors check workspace window for variables >> save demo -OR- click corresponding button look at your folder in My Documents subfolder Clear workspace, check Workspace then Reload variables, check Workspace

Scripts Scripts allow us to group and save MatLab commands for future use If we make an error, we can edit statements and commands Can modify later to solve other related problems Script is the MatLab terminology for a program NOTE: Scripts may use variables already defined in the workspace. –This can lead to unexpected results. –It is a good idea to clear the workspace (and the command window) at the beginning of all scripts. clear, clc

M-files: Scripts A Script is the simplest example of an M-file. When a script-file is invoked, MatLab simply executes the commands found in the file. Any variables created in the script are added to the MatLab Workspace. Scripts are particularly useful for automating long sequences of command.

Writing a MATLAB Script (program) File  New  M-File usually start with: clear, clc, format compact comments after % –for in-class exercises include at least: Course, date,section & # (e.g. EF105, Monday 8:00 ) a short title your name semi-colons to suppress variable initialization –omit semi-colons to display results –You can leave off ALL semi-colons to trace a program

Matlab Editor (note "Save and Run" button) Color keyed text with auto indents tabbed sheets for other files being edited Access to commands

Script Files (filename.m) Always check Current Directory Window –Set to MyDocuments\username Running scripts –from editor window, click "Save and run" button –-or- just type filename: –-or- type run filename

Hands-On DEMO: Creating our First Script (factorial) %fact_n – Compute n-factorial, n!=1*2*...*n % by DFJ fact = prod(1:n) % no semi-colon so fact displays %fact_n – Compute n-factorial, n!=1*2*...*n % by DFJ fact = prod(1:n) % no semi-colon so fact displays File  New  M-File File  Save As... fact_n Operates on a variable in "global" workspace –Variable n must exist in workspace –Variable fact is created (or over-written)

Hands-On DEMO: Running your Script To Run just type >> n=5; >> fact_n -OR- >> n=10; >> run fact_n

Displaying Code and Getting Help To list code, use type command >> type fact_n The help command displays first consecutive comment lines >> help fact_n

MATLAB Exercise 1 See the Word document for this exercise and perform at end of class on your own!!