Matlab Basics Lecture 2. Juha Kuortti October 28, 2017

Similar documents
Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

f( x ), or a solution to the equation f( x) 0. You are already familiar with ways of solving

An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s.

7 Control Structures, Logical Statements

Programming for Experimental Research. Flow Control

Bisecting Floating Point Numbers

The Bisection Method versus Newton s Method in Maple (Classic Version for Windows)

Reals 1. Floating-point numbers and their properties. Pitfalls of numeric computation. Horner's method. Bisection. Newton's method.

C/C++ Programming for Engineers: Matlab Branches and Loops

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Repetition Structures Chapter 9

Math Scientific Computing - Matlab Intro and Exercises: Spring 2003

Chapter 7: Programming in MATLAB

Files and File Management Scripts Logical Operations Conditional Statements

The New Bisection Plus Algorithm by Namir Shammas

THREE LECTURES ON BASIC TOPOLOGY. 1. Basic notions.

A, B, TOL, C, OK, X, F, FA, FB, I, P, FP;

Introduction to C++ Introduction to C++ Week 6 Dr Alex Martin 2013 Slide 1

Relational and Logical Operators

MATLAB SUMMARY FOR MATH2070/2970

COGS 119/219 MATLAB for Experimental Research. Fall 2016 Week 1 Built-in array functions, Data types.m files, begin Flow Control

MATLAB Laboratory 10/07/10 Lecture. Chapter 7: Flow Control in Programs

Relational and Logical Operators. MATLAB Laboratory 10/07/10 Lecture. Chapter 7: Flow Control in Programs. Examples. Logical Operators.

From: Robert Sharpley Subject: Homeworks #6 Date: February 22, :09:53 AM EST Cc: Robert Sharpley

Exercises C-Programming

Computers in Engineering Root Finding Michael A. Hawker

Today. Golden section, discussion of error Newton s method. Newton s method, steepest descent, conjugate gradient

H.C. Chen 1/24/2019. Chapter 4. Branching Statements and Program Design. Programming 1: Logical Operators, Logical Functions, and the IF-block

Numerical Methods Lecture 1

The New Trisection and Trisection Plus Root- Seeking Algorithms by Namir Shammas

Handout 2 - Root Finding using MATLAB

Section 2.5: Continuity

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Evaluating the polynomial at a point

Introduction to Programming for Engineers Spring Final Examination. May 10, Questions, 170 minutes

Lecture 3 MATLAB programming (1) Dr.Qi Ying

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

CS 221 Lecture. Tuesday, 4 October There are 10 kinds of people in this world: those who know how to count in binary, and those who don t.

Numerical Methods Lecture 7 - Optimization

AC : MATHEMATICAL MODELING AND SIMULATION US- ING LABVIEW AND LABVIEW MATHSCRIPT

A QUICK INTRODUCTION TO MATLAB

Contents. Hilary Term. Summary of Numerical Analysis for this term. Sources of error in numerical calculation. Solving Problems

MATLAB Vocabulary. Gerald Recktenwald. Version 0.965, 25 February 2017

Problem Solving (Computing) Array and Pointer

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

ECE Digital System Design & Synthesis Exercise 1 - Logic Values, Data Types & Operators - With Answers

Chapter - 2 Complexity of Algorithms for Iterative Solution of Non-Linear Equations

A QUICK INTRODUCTION TO MATLAB. Intro to matlab getting started

Boolean Logic & Branching Lab Conditional Tests

2 Homework: Bond class, fair value, duration & yield

LECTURE 0: Introduction and Background

Computational Mathematics

1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 169 / 221

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

Introduction to Julia. HA Van Thao Faculty of Math & Computer Science, HCMUS

Lecture 7 Symbolic Computations

21-Loops Part 2 text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie

Flow Control. Statements We Will Use in Flow Control. Statements We Will Use in Flow Control Relational Operators

Information Theory and Communication

Chapter 4: Programming with MATLAB

Numerical Methods in Engineering Sciences

Relational and Logical Statements

Chapter Goals: Evaluate limits. Evaluate one-sided limits. Understand the concepts of continuity and differentiability and their relationship.

MATLAB Lecture 4. Programming in MATLAB

Fundamentals of the J Programming Language

Relational & Logical Operators

Scope of Variables. In general, it is not a good practice to define many global variables. 1. Use global to declare x as a global variable.

COURSE: NUMERICAL ANALYSIS. LESSON: Methods for Solving Non-Linear Equations

PROGRAM EFFICIENCY & COMPLEXITY ANALYSIS

Chapter 3 Limits and Derivative Concepts

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment

Graph Theory Questions from Past Papers

To start using Matlab, you only need be concerned with the command window for now.

MATH2070: LAB 3: Roots of Equations

Calculus I Review Handout 1.3 Introduction to Calculus - Limits. by Kevin M. Chevalier

And Now to Something Completely Different: Finding Roots of Real Valued Functions

GraphBLAS Mathematics - Provisional Release 1.0 -

Introduction to MATLAB Practical 1

Arithmetic operations

Mathematics. 2.1 Introduction: Graphs as Matrices Adjacency Matrix: Undirected Graphs, Directed Graphs, Weighted Graphs CHAPTER 2

Control Structures. March 1, Dr. Mihail. (Dr. Mihail) Control March 1, / 28

1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225

5. Using the precendence rules for arithmetic operators, determine which statement is true.

Math 230 Final Exam December 22, 2015

Introduction to MATLAB Programming

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Polynomials tend to oscillate (wiggle) a lot, even when our true function does not.

SEQUENCES, MATHEMATICAL INDUCTION, AND RECURSION

Biostatistics 615/815 Lecture 13: Numerical Optimization

Lecture 3: MATLAB advanced use cases

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

5.5 Newton s Approximation Method

Functions of Two Variables

Matlab Tutorial. The value assigned to a variable can be checked by simply typing in the variable name:

Fortran 90 Two Commonly Used Statements

2 Computation with Floating-Point Numbers

1 extrema notebook. November 25, 2012

ENGR 105: Introduction to Scientific Computing. Dr. Graham. E. Wabiszewski

Introduction to MATLAB

Material from Recitation 1

Transcription:

Matlab Basics Lecture 2 Juha Kuortti October 28, 2017 1

Lecture 2 Logical operators Flow Control 2

Relational Operators Relational operators are used to compare variables. There are 6 comparison available: equal to, using == not equal to, using = less than, using < less than or equal to, using <= greater than, using > greater than or equal to, using >= The result of a comparison is either TRUE (1) or FALSE (0). Note that MATLAB does difference between logical value and numerical one, but allows the usual scalar operations to take place. 3

Array comparisons Suppose A and B are double arrays of the same size. Let op be any of the 6 relational operators (==, =, <, <=, >, >=). Then the expression A op B is a logical array of the same size. The relational operator is applied elementwise, comparing A(i, j) to B(i, j). Example: >> A = rand(2,4); >> B = 0.5*ones(2,4); >> A<B 4

Excercise Using meshgrid create a 2d space of matrices X and Y that covers the area [ 4, 4] [ 4, 4]. Then find all the elements in X and Y for which it holds that X(i, j) 2 + Y (i, j) 2 < 2. Call the resulting logical array Z. Finally mesh(x,y,z). 5

Array comparisons The result of a relational operation is a logical array. A logical array contains only 0 s and 1 s It cannot contain any other numerical values Internal representation in MATLAB is different than for double arrays. You can use a logical array in any numerical calculation as though it is a double array; the 0 s and 1 s behave normally. MATLAB automatically typecasts the logicals to doubles. >> A = [1 0 1 1]; >> B = logical(a); >> whos >> A==B >> isequal(a,b) 6

Logical indexing In a typical row/column reference, M(RowIndex, ColIndex) both RowIndex and ColIndex are double arrays, whose positive, integer values specify which rows and columns of the array M are being referenced. If RowIndex and ColIndex are logical arrays, the locations of the 1 s specify which rows and columns of the array M are being referenced. >> M = rand(4,5); >> Ridx = logical([1 0 0 1]); >> Cidx = logical([0 0 1 1 1]); >> M(Ridx,Cidx) %same as M([2 4],[3 4 5]) 7

Using find The command find returns the indices of the nonzero entries of logical statement. >> m = rand(6,1); >> m(find(m<0.5)) = 0; Usually logical indexing will work just fine, so you can just do >> m = rand(6,1); >> m(m<0.5) = 0; 8

More on find However, when you need the actual index, use find. >> P = peaks; >> maxind = find(p==max(p(:))) >> mesh(p); hold on; >> [m,n] = ind2sub(size(p),maxind); >> plot3(n,m,p(maxind),'r*') Sidebar: find will always provide the linear indices (remember those?). In order to transform them to subscript indices we use a function called ind2sub. 9

All things are not equal In finite precision arithmetic (MATLAB has about 17 digits of precision), it is not true that (a + b) + c is equal to a + (b + c) In practice this means that when comparing doubles, equality is not a good test for similarity; instead we usually use abs(x-y)<tol to check for equality. There are also other metrics well learn them as we go. 10

Logical Operators Logical operators are used to operate on logical variables. There are 3 binary operations logical AND, using & logical OR, using logical exclusive OR, using xor There is also the unary operation logical NOT, using For arrays, the operators are applied elementwise, and the results have logical values of TRUE (1) or FALSE (0) In case of scalar values, there are also operators && and, that perform more efficiently. 11

Logical Operators If A and B are scalars (double or logical), then A&B is TRUE (1) if A and B are both nonzero, otherwise it is FALSE (0) A B is TRUE (1) if either A or B are nonzero, otherwise it is FALSE (0) xor(a, B) is TRUE (1) if one argument is 0 and the other is nonzero, otherwise it is FALSE (0) A is TRUE if A is 0, and FALSE if A is nonzero. For arrays, the operations are applied elementwise, so A and B must be the same size, or one must be a scalar. If you wish to check if two arrays are same, use all, if you wish see whether they have any similarities, use any. 12

One notable exception Usually logical operators only function on arrays of equal dimensions, for example testing [1,2,3]==[3,2], will result in an error, rather than FALSE. There is one situation where this will lead to problems: namely, comparing strings. In string context, comparison Hello == Oh, Hel should clearly be FALSE, but will result in an error. For string comparisons, use MATLAB function strcmp. 13

Control:if, end To conditionally control the execution of statements, you can use if expression statements end If the real part of all of the entries of expression are nonzero, then the statements between the if and end will be executed. Otherwise they will not be. If the expression is an array, then the check is implicitly all(expression). Execution continues with any statements after the end. 14

Control:if, else, end if exp1 statements1 else statements2 end One of the sets of statements will be executed If exp1 is TRUE, then statements1 are executed If exp1 is FALSE, then statements2 are executed 15

Control:if, elseif, end If you need to check for multiple cases, use elseif: if exp_1 statements1 elseif exp_2 statements2 elseif exp_3 statements3 end Similar to switch:case:break structure in many other languages: execute statement involved with first true expression, then jump to end. 16

Excercise Create a m-file function for the mathematical function y = f (x) shown below. 17

Lecture 2 Iterations More control. 18

Control: for, end Execute collection of statements a fixed number of times. for x=expression statements end The expression is evaluated once before the loop starts. The value is called the controlvalue. The statements are executed one time for each column in the controlvalue. In the code above, x is the loopvariable. Before each execution pass, the loopvariable (x) is assigned to the corresponding column of controlvalue: 1st column on the first pass, 2nd on second and so on. 19

Control: for, end The most common value for expression is a row vector of integers, starting at 1, and increasing to a limit n. for x=1:n statements end The controlvalue is simply the row vector [1, 2, 3..., n], hence the statements are executed n times. Since The first time through, the value of x is set equal to 1 the k th time through, the value of x is set equal to k. this is an extremely useful way to index an array. 20

Control: for, end The expression can be created before the loop itself, so the loop doubles as foreach type loop. for x=1:n statementxs end is same as xvalues = 1:n; for x=xvalues statements end 21

Example Write a function to compute the of amount owed for a loan amount L, given interest rate R, loan duration T and fixed payments of amount P. 22

Example function P = loancalc(l,r,n,mp) % P = loancalc(l,r,n,mp) computes the % history of amount owed on a loan of amount % L, interest rate R, duration N, and fixed % monthly payment MP. P = zeros(n+1,1); P(1) = L; % amount owed at Month=0 % interest rate R is annual, but applied % monthly, yielding a 1+R/12 factor. G = 1+R/12; for i=2:n+1 P(i) = P(i-1)*G - MP; end 23

Control: while, end If you need to execute commands for an undetermined number of times, use while loop while expression statements end while evaluates expression, and if it is TRUE, then executes the statements, and repeats, otherwise it jumps to end. Notice, that expression need not become FALSE ever, leading to an infinite loop. 24

Example Banach fixed point theorem states (paraphrasing heavily) that if a function f is a contraction, then iteration x n+1 = f (x n ) will converge to a unique fixed point of the function regardless of the starting value x 0, i.e. a point x for which f (x ) = x. Let s use a while and fixed point iteration to find the fixed point of f (x) = cos(x). 25

Application time Tiny bit of numerics Few MATLAB built-ins 26

Basic building blocks Famously, the Bolzano Theorem (later to be refined to intermediate value theorem) states that: If a continuous function, f, with an interval, [a, b], as its domain, takes values f (a) and f (b) at each end of the interval, then it also takes any value between f(a) and f(b) at some point within the interval. More precisely, if we have a continous function that has values of opposite sign inside an interval, then it has a root in that interval. 27

Example: Bisection method Let s apply the following, and write our own solver: this one will be very similar to binary search. Method: given endpoints a and b 1 find the midpoint p in the middle of [a, b]. 2 if f (p) is zero (or close enough) - stop, you ve solved the problem. 3 if f (p) > 0 move the positive end to it, and go to step 1. 4 if f (p) < 0 move the negative end to it, and go to step 1. Since the search interval is halved at each step, the convergence is fairly fast. 28

Example: Bisection method function p = bisection(f,a,b) if f(a)*f(b)>0 disp('iteration is impossible') else tol = 1e-7; p = (a + b)/2; while abs(f(p)) > tol if f(a)*f(p)<0 b = p; else a = p; end p = (a + b)/2; end end 29

Your turn: Newton s method Suppose we have and f (x) = x e x 2 f (x) = 1 + 2xe x 2 Write a function that implements the Newton s method (teachers and Google will help if you ve forgotten what it is), and use it to find the root of f (x). Note: it is technically possible to select a starting location so that the method does not converge implement an iteration counter that stops the method after a large number of iteration has passed and solution has not been found to avoid an infinite loop. 30