MATLAB Review Selim Aksoy Bilkent University Department of Computer Engineering

Slides:



Advertisements
Similar presentations
A number of MATLAB statements that allow us to control the order in which statements are executed in a program. There are two broad categories of control.
Advertisements

COMP 116: Introduction to Scientific Programming Lecture 37: Final Review.
Introduction to Matlab
User-defined Functions Selim Aksoy Bilkent University Department of Computer Engineering
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Programming with MATLAB
Chapter 7. Even in quantitative sciences, we often encounter letters and/or words that must be processed by code You may want to write code that: Reads.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Lecture 8 Logical Operations Logical functions & Relational operators © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
Arrays Revisited Selim Aksoy Bilkent University Department of Computer Engineering
Additional Data Types: 2-D Arrays, Logical Arrays, Strings Selim Aksoy Bilkent University Department of Computer Engineering
MATLAB Basics CS 111 Introduction to Computing in Engineering and Science.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Week 7 - Programming I Relational Operators A > B Logical Operators A | B For Loops for n = 1:10 –commands end.
Top-down Program Design, Relational and Logical Operators
Vectors and Plotting Selim Aksoy Bilkent University Department of Computer Engineering
User-defined Functions Selim Aksoy Bilkent University Department of Computer Engineering
Program Design, Relational and Logical Operators Selim Aksoy Bilkent University Department of Computer Engineering
CS241 PASCAL I - Control Structures1 PASCAL I - Control Structures Philip Fees CS241.
Additional Data Types: 2-D Arrays, Logical Arrays Selim Aksoy Bilkent University Department of Computer Engineering
Introduction to MATLAB
Additional Data Types: Strings Selim Aksoy Bilkent University Department of Computer Engineering
MATLAB Strings Selim Aksoy Bilkent University Department of Computer Engineering
Relational and Logical Operators Selim Aksoy Bilkent University Department of Computer Engineering
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 and SimulinkLecture 11 To days Outline  Introduction  MATLAB Desktop  Basic Features  Branching Statements  Loops  Script file / Commando.
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.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Introduction to MATLAB. Windows in MATLAB Command Window – where you enter data, run MATLAB code, and display results Command History - displays a log.
Slide deck by Dr. Greg Reese Miami University MATLAB An Introduction With Applications, 5 th Edition Dr. Amos Gilat The Ohio State University Chapter 6.
ECE 1304 Introduction to Electrical and Computer Engineering Section 1.1 Introduction to MATLAB.
COMP 116: Introduction to Scientific Programming Lecture 28: Midterm #2 Review.
MATLAB Tutorial EE 327 Signals and Systems 1. What is MATLAB? MATLAB – Matrix Laboratory The premier number-crunching software Extremely useful for signal.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Matlab Programming for Engineers Dr. Bashir NOURI Introduction to Matlab Matlab Basics Branching Statements Loops User Defined Functions Additional Data.
CMPS 1371 Introduction to Computing for Engineers CONDITIONAL STATEMENTS.
10/24/20151 Chapter 2 Review: MATLAB Environment 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 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”
MATLAB 及其工程应用 MATLAB and It’s Engineering Application 主讲教师: 胡章芳
Structured Programming I – Relational & Logical Operators Objectives: By the end of this class you should be able to: Change graph interactively in EXCEL.
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.
MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.
Matlab Programming for Engineers
Digital Image Processing Lecture 6: Introduction to M- function Programming.
CS241 PASCAL I - Control Structures1 PASCAL Control Structures Modified Slides of Philip Fees.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
CMPS 1371 Introduction to Computing for Engineers CHARACTER STRINGS.
1. Comparing Strings 2. Converting strings/numbers 3. Additional String Functions Strings Built-In Functions 1.
Interduction to MATLAB (part 2) Manal Alotaibi Mathematics department College of science King saud university.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
1 Structured Programming EEN170 Programming in MATLAB.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
ECE 1304 Introduction to Electrical and Computer Engineering
The Selection Structure
MATLAB DENC 2533 ECADD LAB 9.
Introduction to MATLAB
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
String Manipulation Chapter 7 Attaway MATLAB 4E.
T. Jumana Abu Shmais – AOU - Riyadh
Logical Operations In Matlab.
Matlab Basics.
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Presentation transcript:

MATLAB Review Selim Aksoy Bilkent University Department of Computer Engineering

Spring 2004CS 1112 MATLAB MATLAB Basics Top-down Program Design, Relational and Logical Operators Branches and Loops Vectors and Plotting User-defined Functions Additional Data Types: 2-D Arrays, Logical Arrays, Strings Input/Output Functions

Spring 2004CS 1113 MATLAB Basics: Variables Initialization using shortcut statements colon operator  first:increment:last x = 1:2:10 x = y = 0:0.1:0.5 y =

Spring 2004CS 1114 MATLAB Basics: Variables Initialization using keyboard input input() value = input( 'Enter an input value: ' ) Enter an input value: 1.25 value = name = input( 'What is your name: ', 's' ) What is your name: Selim name = Selim

Spring 2004CS 1115 MATLAB Basics: Subarrays Array indices start from 1 x = [ ]; x(2) ans = 0 x(4) ans = 1 x(8) ??? Error x(-1) ??? Error

Spring 2004CS 1116 MATLAB Basics: Subarrays y = [ 1 2 3; ]; y(1,:) ans = y(:,2) ans = 2 5 y(2,1:2) ans = 4 5 y(1,2:end) ans = 2 3 y(:,2:end) ans =

Spring 2004CS 1117 MATLAB Basics: Subarrays y = [ 1 2 3; ]; y(1,2) = -5 y = y(2,1) = 0 y = y(1,2:end) = [ -1 9 ] y = y = [ 1 2 3; 4 5 6; ]; y(2:end,2:end) = 0 y = y(2:end,2:end) = [ -1 5 ] ??? Error y(2,[1 3]) = -2 y =

Spring 2004CS 1118 MATLAB Basics: Displaying Data The disp( array ) function disp( 'Hello' ); Hello disp(5); 5 disp( [ 'Bilkent ' 'University' ] ); Bilkent University name = 'Selim'; disp( [ 'Hello ' name ] ); Hello Selim

Spring 2004CS 1119 MATLAB Basics: Displaying Data The fprintf( format, data ) function %dinteger %ffloating point format %eexponential format \nnew line character \ttab character Examples: fprintf( 'Result is %d', 3 ); Result is 3 fprintf( 'Area of a circle with radius %d is %f', 3, pi*3^2 ); Area of a circle with radius 3 is x = pi; fprintf( 'x = %0.2f', x ); x = 3.14

Spring 2004CS Programming Rules of Thumb Learn program patterns of general utility (branching, loops, etc.) and use relevant patterns for the problem at hand Seek inspiration by systematically working test data by hand and ask yourself: “what am I doing?” Declare variables for each piece of information you maintain when working problem by hand Decompose problem into manageable tasks Remember the problem’s boundary conditions Validate your program by tracing it on test data with known output

Spring 2004CS Relational Operators Relational operators are used to represent conditions where the result of the condition is either true or false In MATLAB, false is represented by 0 and true is represented by 1 (non-zero) Don’t confuse equivalance (==) with assignment (=) Be careful about roundoff errors during numeric comparisons (you can represent “x == y” as “abs(x-y) < eps”)

Spring 2004CS Logical Operators inputandorxornot aba & ba | bxor(a,b)~a

Spring 2004CS Operator Hierarchy Processing order of operations: parenthesis (starting from the innermost) ~ operators exponentials (left to right) multiplications and divisions (left to right) additions and subtractions (left to right) relational operators (left to right) & operators (left to right) | operators (left to right)

Spring 2004CS Branches Branches are used to select and execute specific sections of the code while skipping other sections Selection of different sections depend on a condition statement We learned: if statement switch statement

Spring 2004CS Branches: “if” Statement Conditions can be: any real value (0 is false, non-zero is true) combination of relational and logical operators e.g. ( x > 0 ) & ( x < 10 ) logical functions isempty() isnumeric(), ischar() isinf(), isnan() exist()

Spring 2004CS Branches: “if-elseif-else” Statement if ( condition 1 ), statement 1 statement 2... elseif ( condition 2 ), statement 1 statement 2... else statement 1 statement 2... end statement group 1 condition 1 statement group 1 truefalse condition 2 statement group 2 statement group 3 truefalse statement group 2 statement group 3

Spring 2004CS Branches: “switch” Statement switch ( expression ), case {value set 1}, statement 1 statement 2... case {value set 2}, statement 1 statement 2... otherwise, statement 1 statement 2... end statement group 1 statement group 2 optional statement group that is executed if none of the cases is satisfied

Spring 2004CS Loops Loops are used to execute a sequence of statements more than once We learned: while loop for loop They differ in how the repetition is controlled

Spring 2004CS Loops: “while” Loop Statements are executed indefinitely as long as the condition is satisfied while ( condition ), statement 1 statement 2... end statement group condition statement group true false

Spring 2004CS Loops: “for” Loop Statements are executed a specified number of times for index = expression, statement 1 statement 2... end Expression is usually a vector in shortcut notation first:increment:last statement group

Spring 2004CS Loops: “break/continue” Statements Break statement terminates the execution of a loop and passes the control to the next statement after the end of the loop Continue statement terminates the current pass through the loop and returns control to the top of the loop

Spring 2004CS Advice Use indentation to improve the readability of your code Never modify the value of a loop index inside the loop Allocate all arrays used in a loop before executing the loop If it is possible to implement a calculation either with a loop or using vectors, always use vectors Use built-in MATLAB functions as much as possible instead of reimplementing them

Spring 2004CS Initializing Vectors linspace(x1,x2) generates a row vector of 100 linearly equally spaced points between x1 and x2 linspace(x1,x2,N) generates N points between x1 and x2 x = linspace(10,20,5) x = logspace(x1,x2) can be used for logarithmically equally spaced points

Spring 2004CS Vector Input to Functions You can call built-in functions with array inputs The function is applied to all elements of the array The result is an array with the same size as the input array

Spring 2004CS Vector Operations Vector-vector operations (element-by-element operations) x = [ ]; y = [ ]; z = x + y z = z = x.* y z = z = x./ y z =

Spring 2004CS Vector Operations Vector-vector operations (element-by-element operations) z = x.^ y z = Use.*,./,.^ for element-by-element operations Vector dimensions must be the same

Spring 2004CS Plotting Summary plot(x,y) linear plot of vector y vs. vector x title('text'), xlabel('text'), ylabel('text') labels the figure, x-axis and y-axis axis( [ xmin xmax ymin ymax ] ) sets axes’ limits legend( 'string1', 'string2', 'string3',... ) adds a legend using the specified strings hold on/off allows/disallows adding subsequent graphs to the current graph

Spring 2004CS Scripts A script is just a collection of MATLAB statements Running a script is the same as running the statements in the command window Scripts and the command window share the same set of variables, also called global variables

Spring 2004CS Functions A function is a black box that gets some input and produces some output We do not care about the inner workings of a function Functions provide reusable code Functions simplify debugging Functions have private workspaces The only variables in the calling program that can be seen by the function are those in the input list The only variables in the function that can be seen by the calling program are those in the output list

Spring 2004CS Function Examples function [ cnt, pos ] = strsearch( s, c ) %STRSEARCH find the number of occurrences of a character in a string % Function STRSEARCH finds the number of occurrences of a character % c in a given string s. It returns both the index of the first % occurrence and the number of occurrences. % It returns 0 for both the index and the number of occurrences if % c does not exists in s. % % By Pinar Senkul, 24/10/2003 pos = 0; cnt = 0; n = length(s); for ii = n:-1:1, if ( s(ii) == c ), cnt = cnt + 1; pos = ii; end two variables declared as output arguments two variables declared as input arguments other comment lines executable code H1 comment line

Spring 2004CS D Arrays Adding the elements of a matrix function s = sum_elements(a) [r,c] = size(a); s = 0; for ii = 1:r, for jj = 1:c, s = s + a(ii,jj); end end

Spring 2004CS Logical Arrays Created by relational and logical operators Can be used as masks for arithmetic operations A mask is an array that selects the elements of another array so that the operation is applied to the selected elements but not to the remaining elements

Spring 2004CS Logical Arrays Examples b = [ 1 2 3; 4 5 6; ] b = c = b > 5 c = whos Name Size Bytes Class a 2x4 64 double array b 3x3 72 double array c 3x3 72 double array (logical)

Spring 2004CS Strings A string is an array of characters s = 'abc' is equivalent to s = [ 'a' 'b' 'c' ] All operations that apply to vectors and arrays can be used together with strings as well s(1)  'a' s( [ 1 2 ] ) = 'XX'  s = 'XXc' s(end)  'c'

Spring 2004CS Character Arrays 2-D character arrays s = [ 'my first string'; 'my second string' ] ??? Error s = char( 'my first string', 'my second string' ) s = my first string my second string size(s)  [ 2 16 ] size( deblank( s(1,:) ) )  [ 1 15 ] char function automatically pads strings

Spring 2004CS String Functions ischar(), isletter(), isspace() strcmp() : returns 1 if two strings are identical upper(): Lowercase-to-uppercase lower() : Uppercase-to-lowercase findstr() : finds one string within another one strtok() : finds a token in a string strrep() : replaces one string with another num2str(), str2num() sprintf() is identical to fprintf() but output is a string