EL2310 Scientific Programming

Similar documents
EL2310 Scientific Programming

Lecture 3. Introduction to Matlab

MATLAB Operators, control flow and scripting. Edited by Péter Vass

Introduction to Matlab

MATLAB Second Seminar

SECTION 2: PROGRAMMING WITH MATLAB. MAE 4020/5020 Numerical Methods with MATLAB

Mini-Matlab Lesson 5: Functions and Loops

MATLAB TUTORIAL WORKSHEET

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

LECTURE 1. What Is Matlab? Matlab Windows. Help

INTRODUCTION TO MATLAB, SIMULINK, AND THE COMMUNICATION TOOLBOX

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

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

SECTION 5: STRUCTURED PROGRAMMING IN MATLAB. ENGR 112 Introduction to Engineering Computing

Lab of COMP 406 Introduction of Matlab (III) Programming and Scripts

Variable Definition and Statement Suppression You can create your own variables, and assign them values using = >> a = a = 3.

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)

MATLAB Introductory Course Computer Exercise Session

Introduction to Matlab

Introduction to Matlab

User Defined Functions

Eng Marine Production Management. Introduction to Matlab

Chapter 1 Introduction to MATLAB

Introduction to Matlab

Tentative Course Schedule, CRN INTRODUCTION TO SCIENTIFIC & ENGINEERING COMPUTING BIL 108E, CRN24023 LECTURE # 5 INLINE FUNCTIONS

CS227-Scientific Computing. Lecture 3-MATLAB Programming

LECTURE 0: Introduction and Background

INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD. July 2018

What is a Function? EF102 - Spring, A&S Lecture 4 Matlab Functions

Matlab Primer. Lecture 02a Optical Sciences 330 Physical Optics II William J. Dallas January 12, 2005

Computational Photonics, Summer Term 2012, Abbe School of Photonics, FSU Jena, Prof. Thomas Pertsch

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

Image Processing Matlab tutorial 2 MATLAB PROGRAMMING

Repetition Structures Chapter 9

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY

Practical 4: The Integrate & Fire neuron

Introduction to MATLAB. Simon O Keefe Non-Standard Computation Group

MATLAB Lesson I. Chiara Lelli. October 2, Politecnico di Milano

Programming in MATLAB

EL2310 Scientific Programming

Outline. User-based knn Algorithm Basics of Matlab Control Structures Scripts and Functions Help

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

Writing MATLAB Programs

MATLAB Project: Getting Started with MATLAB

APPM 2460: Week Three For, While and If s

Introduction to MATLAB

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

Stokes Modelling Workshop

Chapters 6-7. User-Defined Functions

How to program with Matlab (PART 1/3)

Physics 326G Winter Class 6

Question. Insight Through

17 USING THE EDITOR AND CREATING PROGRAMS AND FUNCTIONS

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

MATLAB Programming for Numerical Computation Dr. Niket Kaisare Department Of Chemical Engineering Indian Institute of Technology, Madras

University of Alberta

Computer Vision. Matlab

Introduction to GNU-Octave

Short Version of Matlab Manual

Flow Control and Functions

Lecturer: Keyvan Dehmamy

Attia, John Okyere. Control Statements. Electronics and Circuit Analysis using MATLAB. Ed. John Okyere Attia Boca Raton: CRC Press LLC, 1999

Introduction to MATLAB

Introduction to MATLAB Programming. Chapter 3. Linguaggio Programmazione Matlab-Simulink (2017/2018)

CS 221 Lecture. Tuesday, 13 September 2011

EE168 Handout #6 Winter Useful MATLAB Tips

Scilab Programming. The open source platform for numerical computation. Satish Annigeri Ph.D.

Laboratory 1 Octave Tutorial

What is Matlab? The command line Variables Operators Functions

ECE 202 LAB 3 ADVANCED MATLAB

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

MATLAB Project: Getting Started with MATLAB

Files and File Management Scripts Logical Operations Conditional Statements

Structure Array 1 / 50

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Laboratory 5: Implementing Loops and Loop Control Strategies

Chapter 3: Programming with MATLAB

Lab 12: Numerical Differentiation and Integration

MATLAB Part 2. This week we will look at techniques which will allow you to build powerful applications in MATLAB

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

CS129: Introduction to Matlab (Code)

MATLAB Tutorial. Digital Signal Processing. Course Details. Topics. MATLAB Environment. Introduction. Digital Signal Processing (DSP)

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

FOR LOOP. for <indexmin:indexstep:indexmax> {statements} end

Machine Learning Exercise 0

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

Variables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB:

This is the basis for the programming concept called a loop statement

MATLAB for MAPH 3071 Lab 2

Pace University. Fundamental Concepts of CS121 1

Introduction to MATLAB

EE 301 Signals & Systems I MATLAB Tutorial with Questions

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

Getting started with MATLAB

MATLAB. MATLAB Review. MATLAB Basics: Variables. MATLAB Basics: Variables. MATLAB Basics: Subarrays. MATLAB Basics: Subarrays

Getting started with MATLAB

C Functions. 5.2 Program Modules in C

Desktop Command window

LECTURE 5 Control Structures Part 2

Conditionals & Loops /

Transcription:

(pronobis@kth.se)

Overview Overview Wrap Up More on Scripts and Functions Basic Programming Lecture 2 Lecture 3 Lecture 4

Wrap Up Last time Loading data from file: load( filename ) Graphical input and keyboard input: ginput and input Pausing and drawing now: pause, pause(n), drawnow Scripts and functions scope inputs and outputs comments with % The path: path, addpath, pathtool

Wrap Up Today More on programming in matlab flow control: selection and repetition checking input and output arguments Tips for faster code Timing, debugging and profiling

Wrap Up Remember: What files are run Matlab cannot tell if an identifier is a variable or a function Resolved by picking first match from 1. variable in current workspace 2. built-in variable (like pi, i) 3. built-in m-file 4. m-file in current directory 5. m-file in path

Wrap Up A word on rounding round: round to the nearest integer fix: round to nearest integer towards zero floor: round to the nearest integer towards -inf ceil: round to the nearest integer towards +inf

More on Scripts and Functions Script / Function Basics You run them by typing filename Can also run from the MATLAB editor A function should have the same filename as the function name Do not need to compile m-files (like for C/C++, JAVA, etc) Interpreted as they are run Downside: might not find error until run-time (editor will do syntax check)

More on Scripts and Functions Scripts Lines in script executed as if on command line Operates on base workspace variables Ex script: % Calculate factorial y = prod(1:n); What is needed for it to run? How will the workspace be changed?

More on Scripts and Functions Functions Header: function[out1, out2] = myfunction(in1, in2) Defines max number of input and output arguments but not minimum A variable used in the function must be passed in or be given value in some other way (see later) Remember that local variables exist only in local scope Ex function: function [y] = factorial(n) % y=factorial(n) - Calculates the factorial y = prod(1:n); y is a local variable here

More on Scripts and Functions Returning values from a function You can return values from a function at any time with: return Interrupts the execution and returns to where the function was invoked Current values of variables corresponding to returned values are used There is an implicit return at the end of the function

Basic Programming Branching with if Often want to control the flow depending on the value of some variable if-elseif-else construction if <logical expression> <commands> elseif <logical expression> <commands> else <commands> end Can have any number of commands in between Can have many elseif Do not forget the last end

Basic Programming Relations == equal to < less than <= less than or equal to = not equal to > greater than >= greater than or equal to

Basic Programming Logical operators and functions Logical Operators & and or not Short-circuit Operators A && B - B not evaluated if A==0 A B - B not evaluated if A==1 Functions xor(a,b) exclusive or (exactly one of 2 is true) isempty(a) check if argument is an empty array [] any(a,dim) check if any element is non-zero all(a,dim) check if all elements are non-zero

Basic Programming Verify correct input What happens with our function factorial for argument -2 Look at real factorial function Need to check that inputs are correct

Basic Programming Branching with switch Useful with many == expressions switch <variable> case <value> <commands> case <value> <commands> otherwise <commands> end Commands associated with first true case executed, or otherwise if no true case All commands until next case, otherwise or end are executed

Basic Programming nargin and nargout Can check how many input and output arguments were given nargin: number of inputs arguments nargout: number of output arguments Typically: Let nargin and nargout define what is done Check nargin and give default values if not given

Basic Programming Repetition with for for-loops allow you to loop over some value for <loop variable> = <vector> <commands> end You can define the vector in any of the many ways we saw before Ex: (cumulative sum) sum = 0; for v = values sum = sum + v; end

Basic Programming Repetition with while while <condition> <commands> end for-loops good when you know which values to loop over in advance while-loops when repeating something until some criteria is fulfilled Ex: Repeat approximation until the error is small enough

Basic Programming Tips Avoid loops Use matrix operations Pre-allocate memory

Basic Programming Breaking a repetition Sometimes you want to break out of a repetition Use break command Will continue after the end statement of the for/while loop

Basic Programming Skip to next iteration Sometimes you want to start the next iteration Use continue command Will go up to the for/while statement again

Basic Programming Next time Closing our MATLAB introduction with some more on programming and making movies.

Lecture 2 Task 2.1 Generate a vector of normally distributed values Check mean and standad deviation Generate two sequences and check covariance

Lecture 2 Task 2.2 + 2.3 Load data from linedata.mat Try to fit line to the data Plot the data from the line Plot your line approximation

Lecture 3 Task 3.1 Load data from gyrosignal.txt Collected from a gyro while standing still Format: Each row contains time and gyrosignal The time is in seconds The gyrosignal is in rad/s (maybe biased) Task: 1. Remove any bias 2. integrate the signal to find the angle estimate

Lecture 3 Task 3.2 Display the function z = 1 x 2 + y 2 Use the interval x, y [ 1, 1]

Lecture 3 Task 3.3 Write scripts / functions that Ask the reader to click in a window to enter some data Display the points in the graph Fit a line to them Calculate the mean squared error between the points and the line

Lecture 4 Task 4.1 Write function that return a string with the season given the average temperature

Lecture 4 Task 4.2 Investigate nargin and nargout What happens if not all inputs and outputs are used?

Lecture 4 Task 4.3 Example of pre-allocation: tic <initialization> n = 1000; for k=1:n X(k,k) = 2*k; end toc Investigate with initializations 1. X=[] 2. X=zeros(n,n) 3. What if you built it directly in one command?

Lecture 4 Task 4.4 Write a function that finds a solution to: f (x) = e x sin(x) = 0 Newtons method: x n+1 = x n f (xn) f (x n) Assume initial guess x 0 is given Iterate at most maxit time Stop if x n x n 1 tol