Weizmann 2010 © 1 Introduction to Matlab & Data Analysis Tutorial 10: How to Write Efficient Programs in Matlab Please change directory to directory E:\Matlab.

Slides:



Advertisements
Similar presentations
Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University
Advertisements

© 2006 Pearson Addison-Wesley. All rights reserved10 A-1 Chapter 10 Algorithm Efficiency and Sorting.
Introduction to MATLAB The language of Technical Computing.
Introduction to Matlab Workshop Matthew Johnson, Economics October 17, /13/20151.
Fundamentals of Python: From First Programs Through Data Structures
Programming in Visual Basic
Introduction to Matlab & Data Analysis
CMPT 225 Sorting Algorithms Algorithm Analysis: Big O Notation.
Ver. 1.0 Session 5 Data Structures and Algorithms Objectives In this session, you will learn to: Sort data by using quick sort Sort data by using merge.
CSC401 – Analysis of Algorithms Lecture Notes 1 Introduction
Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.
CIS 101: Computer Programming and Problem Solving Lecture 7 Usman Roshan Department of Computer Science NJIT.
Arrays Revisited Selim Aksoy Bilkent University Department of Computer Engineering
Computer Science in Practice This course is an introduction to problems (and solutions) that arise in applied fields of computer science such as machine.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Computer Science in Practice This course is an introduction to problems (and solutions) that arise in applied fields of computer science such as machine.
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
Programming Logic and Design Fourth Edition, Comprehensive
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Extending MATLAB Write your own scripts and/or functions Scripts and functions are plain text files with extension.m (m-files) To execute commands contained.
Matlab tutorial course Lesson 2: Arrays and data types
CS223 Algorithms D-Term 2013 Instructor: Mohamed Eltabakh WPI, CS Introduction Slide 1.
Solving Scalar Linear Systems Iterative approach Lecture 15 MA/CS 471 Fall 2003.
Nonparametric Econometrics1 Intro to Matlab for Data Analysis and Statistical Modeling.
Yuval Hart, Weizmann 2010© 1 Introduction to Matlab & Data Analysis Tutorial 13: That’s all, Folks! Please change directory to directory E:\Matlab (cd.
General Computer Science for Engineers CISC 106 Lecture 07 James Atlas Computer and Information Sciences 06/29/2009.
SEARCHING, SORTING, AND ASYMPTOTIC COMPLEXITY Lecture 12 CS2110 – Fall 2009.
1 Chapter 24 Developing Efficient Algorithms. 2 Executing Time Suppose two algorithms perform the same task such as search (linear search vs. binary search)
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Introduction to Matlab & Data Analysis
Chapter 19: Searching and Sorting Algorithms
SEARCHING UNIT II. Divide and Conquer The most well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (1): Introduction.
© 2011 Pearson Addison-Wesley. All rights reserved 10 A-1 Chapter 10 Algorithm Efficiency and Sorting.
Chapter 10 A Algorithm Efficiency. © 2004 Pearson Addison-Wesley. All rights reserved 10 A-2 Determining the Efficiency of Algorithms Analysis of algorithms.
Introduction to MATLAB Session 3 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2011.
CSIS 123A Lecture 9 Recursion Glenn Stevenson CSIS 113A MSJC.
10/24/20151 Chapter 2 Review: MATLAB Environment Introduction to MATLAB 7 Engineering 161.
CSC 211 Data Structures Lecture 13
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
COMP 116: Introduction to Scientific Programming Lecture 11: Functions.
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
New Mexico Computer Science For All Algorithm Analysis Maureen Psaila-Dombrowski.
Introduction to MATLAB Session 1 Simopekka Vänskä, THL 2010.
ITC Research Computing Support Using Matlab Effectively By: Ed Hall Research Computing Support Center Phone: Φ Fax:
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure.
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.
Introduction to Matlab Part II 1Daniel Baur / Introduction to Matlab Part II Daniel Baur / Michael Sokolov ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 23 Algorithm Efficiency.
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
The Hashemite University Computer Engineering Department
Image Processing A Study in Pixel Averaging Building a Resolution Pyramid With Parallel Computing Denise Runnels and Farnaz Zand.
Chapter 8 Searching and Sorting © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Searching Topics Sequential Search Binary Search.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Search Algorithms Written by J.J. Shepherd. Sequential Search Examines each element one at a time until the item searched for is found or not found Simplest.
Chapter 4 MATLAB Programming MATLAB Troubleshooting Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
A L I MAM M OHAMMAD B IN S AUD I SLAMIC U NIVERSITY C OLLEGE OF S CIENCES D EPARTMENT OF M ATHEMATICS MATLAB 251 : MATH SOFTWARE Introduction to MATLAB.
1 Introduction to Matlab. 2 What is Matlab? Matlab is basically a high level language which has many specialized toolboxes for making things easier for.
COP 3503 FALL 2012 Shayan Javed Lecture 15
Matlab Training Session 4: Control, Flow and Functions
Introduction to Programming
Scripts & Functions Scripts and functions are contained in .m-files
Searching, Sorting, and Asymptotic Complexity
Algorithm Efficiency and Sorting
Algorithm Course Algorithms Lecture 3 Sorting Algorithm-1
Presentation transcript:

Weizmann 2010 © 1 Introduction to Matlab & Data Analysis Tutorial 10: How to Write Efficient Programs in Matlab Please change directory to directory E:\Matlab (cd E:\Matlab;) From the course website ( ) Download: matlab_t10.zip OR t10.m, sumConsecutiveKNums.m, sumConsecutiveKNumsFixed.m, writingEfficientCodeExamples.m, computeSinSlowAndFast.m, computeSinFast.m, computeSinSlow.m, twinPeaksExample.m, computeTwinPeaksFunc.m,, computeTwinPeaksFuncForSinglePoint.m, findPsychoScore.m

2 Goals M-lint Just-In-Time accelerator Profiler Example of efficient vs. non- efficient algorithm: Binary search Resource:

3 Before We Start Correct code is always more important than speed Keep your code readable Optimize the bottlenecks

4 M-lint Check Code Report edit sumConsecutiveKNums.m Tools -> M lint -> Show M lint report %#ok – ignore this line Advanced: Preference -> M-lint The M-Lint Code Check Report displays potential errors and problems, as well as opportunities for improvement in your code

5 M-lint Check Code Report – Lets Fix the Example Fix: sumConsecutiveKNums.m Tools -> M lint -> Show M lint report Save it as sumConsecutiveKNumsFixed.m Compare the files using: Tools -> Compare against -> Browse

6 Comparing Files – Compare the Fixed File to the Original sumConsecutiveKNums.msumConsecutiveKNumsFixed.m

7 More about M-lint

Weizmann 2010 © 8 Accelerating Your Code Resources: echdoc/matlab_prog/ch7_pe10.html echdoc/matlab_prog/ch7_pe10.html -up-matlab-applications/

9 Write Efficient Code by Using Efficient Algorithms and Efficient Implementation Efficient algorithm Examples: Binary search Bubble sort Efficient implementation Examples: Using vectors manipulation instead of loops Allocating memory in advance Matlab tries to accelerate the code running speed…

10 Matlab Goal is to Convert the M-code Into the Most Efficient Computer Language Code Goal: Best computer language code Computer language Intermediate language x = linspace(0,2*pi,1000); y = sin(x); x = linspace(0,2*pi,1000); z = zeros(size(x)); for i=1:length(x) z(i) = sin(x(i)); end ==

11 Matlab Just-In-Time Accelerator Improving the speed of M-code functions and scripts, particularly self-contained loops.

12 Matlab Just-In-Time Accelerator Matlab 6.5 and later versions Not supported (not accelerated): Cell, Structure, sparse matrix Arrays of more than three dimensions Changing the data type or the shape of an array Calling non built-in functions (M-files) if, elseif, while, and switch – if the logical expression does not evaluate to a scalar Matlab can represent sparse matrices. Checkout sparse doc

13 Timing a Run We can time a run by planting in the code, function that measure the run time: tic, toc cputime Examples: CPU time – The amount of time a computer program uses in processing on a CPU prev_cpu_time = cputime; a = rand(1,100000); cur_cpu_time = cputime; cpu_run_time = … cur_cpu_time-prev_cpu_time run_time = Elapsed time is seconds. tic; a = rand(1,100000); toc; Recommended

14 Matlab Profiler Helps us to Focus on the Code Bottlenecks Profiling - is a way to measure where the program spends its time Profiling helps to uncover performance problems that you can solve by: Avoiding unnecessary computation. Changing your algorithm to avoid costly functions Avoiding recomputation by storing results for future use

15 Matlab Can Produce a Graphical Profiling Report profile('on'); profile('viewer'); profsave(profile('info'),… 'example_profile'); Turning the profiler on Turning the profiler off and presenting the results Saving the profiler results in HTML format

16 Profiler Example - 1 edit writingEfficientCodeExamples.m; Lets run the first example: profile('on'); vec1 = linspace(0,2*pi,10^4); [vec1_sin_fast vec1_sin_slow] = computeSinSlowAndFast(vec1); profile('viewer'); profsave(profile('info'),'example1_profile');

17 Profiler Example 1 – Profile Summary Dark band – self time

18 Profiler Example 1 – Focusing on a Function

19 Function listing highlights time consumintg lines

20 The Profiler Gives Also the M-lint Analysis

21 Profiler Example - 2 Try run the second example: In function computeTwinPeaksFunc: Try to change to computation of Z to a function: How does it affect the code? Why? Try saving the profiler results in HTML format using: profile('on'); twinPeaksExample(); profile('viewer'); %Z(i,j) = X(i,j) * exp(X(i,j)^2-Y(i,j)^2); Z(i,j) = computeTwinPeaksFuncForSinglePoint(X(i,j),Y(i,j)); profsave(profile('info'),'example2_profile');

Weizmann 2010 © 22 Efficient vs. Non- Efficient Algorithm Binary search (Lecture Reminder)

23 Divide and Conquer Paradigm Since the lion is dangerous we can’t catch him, so we start building fences until we close him in a cage… First Strategy: How do you catch a lion in the desert?

24 Divide and Conquer Paradigm Divide and conquer strategy (“lion in the desert”): How do you catch a lion in the desert?

25 Implementation of binary search We have data sets of last psychometric exam results We want to write a function that: Given an ID, finds its corresponding score as fast as possible IDscore …… Sorted

26 We Will Use the “Lion in the Desert” Strategy – Binary Search Example: Find id = compare IDs = left index / right index = Requested ID

27 Binary Search – IDs example function [id_index] = local_findIdIndexBinary(ids, id) %init id_index = NaN; l_ind = 1; r_ind = length(ids); mid_ind = floor((l_ind + r_ind) / 2);

28 Binary Search – IDs example function [id_index] = local_findIdIndexBinary(ids, id) while l_ind < r_ind cur_mid_id = ids(mid_ind); if id == cur_mid_id id_index = mid_ind; return; elseif id < cur_mid_id r_ind = mid_ind; mid_ind = floor((l_ind + r_ind) / 2); else %id > cur_mid_id l_ind = mid_ind; mid_ind = ceil((l_ind + r_ind) / 2); end l_indr_indmid_ind

29 Performance Comparison of Linear Search and Binary Search Check out t10.m and findPsychoScore.m Results for three search of random id: test: Linear search took comparisons Linear search find that the score of ID is:440 Binary search took 17 comparisons Binary search find that the score of ID is: test: Linear search took 2702 comparisons Linear search find that the score of ID is:571 Binary search took 17 comparisons Binary search find that the score of ID is: test: Linear search took comparisons Linear search find that the score of ID is:720 Binary search took 17 comparisons Binary search find that the score of ID is:720 Comment: Worst case Average case

30 Summary M-lint Just-In-Time accelerator Profiler Example of efficient vs. non- efficient algorithm: Binary search