MATLAB array manipulation tips and tricks Peter J. Acklam Emal: pack⊥ amon1i Url:http://home.onlineno/-pjacklam 1 8th October 2003
MATLAB array manipulation tips and tricks Peter J. Acklam E-mail: pjacklam@online.no URL: http://home.online.no/~pjacklam 18th October 2003
Contents 1 High-level ys low-level code L1 Introduction 1.2 Advantages and disadvantages 1.2. 1 Portability 1. 2.2 Verbosity 1.2.3 Speed 1. 2. 4 Obscurity 1.3 Words of warning 2 Operators, functions and special 2.1 Operators 222334 2.2 Built-in functions 2.3 M-file functions 3 Basic array properties 3.1 Siz 5666 3.1.1 Size along a specific dimension 3.1.2 Size along multiple dimen IsIons 3.2 Dimensions 3.2.1 Number of dimensions 3.3 Number of elements 7778 3.3.1 Empty arrays 4 Array indices and subseripts 5 Creating basic vectors, matrices and arrays 5.1Cr stant 5.1.1 When the class is determined by the scalar to replicate 5.1.2 When the class is stored in a string variable 5.2 Special vectors 000111 6 Shifting 6.1 Vectors 6.2 Matrices and arrays
Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v 1 High-level vs low-level code 1 1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 Advantages and disadvantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2.1 Portability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2.2 Verbosity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.2.3 Speed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.2.4 Obscurity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.2.5 Difficulty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.3 Words of warning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 2 Operators, functions and special characters 3 2.1 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 2.2 Built-in functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 2.3 M-file functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 3 Basic array properties 6 3.1 Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 3.1.1 Size along a specific dimension . . . . . . . . . . . . . . . . . . . . . . . . 6 3.1.2 Size along multiple dimensions . . . . . . . . . . . . . . . . . . . . . . . . 6 3.2 Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3.2.1 Number of dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3.2.2 Singleton dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3.3 Number of elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3.3.1 Empty arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 4 Array indices and subscripts 9 5 Creating basic vectors, matrices and arrays 10 5.1 Creating a constant array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 5.1.1 When the class is determined by the scalar to replicate . . . . . . . . . . . . 10 5.1.2 When the class is stored in a string variable . . . . . . . . . . . . . . . . . . 11 5.2 Special vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 5.2.1 Uniformly spaced elements . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 6 Shifting 12 6.1 Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 6.2 Matrices and arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 ii
CONTENTS 7 Replicating elements and arrays 7.1 Creating a constant array 7.2 Replicating elements in vectors 13 7.2.1 Replicate each element a constant number of times 7.2.2 Replicate each element a variable number of times 13 7.3 Using KRON for replicating elements 73.1 KRoN with an matrix of ones 7.3.2 KRON with an identity matrix 8 Reshaping arrays 8.1 Subdividing 2D matrix 8.1.1 Create 4D array 8.1.2 Create 3D array (columns first) 8.1.3 Create 3D array (rows first) 66677 8.1.4 Create 2D matrix(columns firs St cOIumn ou 8.1.5 Create 2D matrix(columns first, row output) 8.1.6 Create 2D matrix(rows first, column output) 8.1.7 Create 2D matrix(rows first, row output) 78899 8.2 Stacking and unstacking pages Rotating matrices and arrays 9.1 Rotating 2D matrices 9.2 Rotating ND arrays 9.3 Rotating ND arrays around an arbitrary axis 9.4 Block-rotating 2D matrices 9 4.1"Inner" vs"outer block rotation 001223 9.4.2"Inner" block rotation 90 degrees counterclockwise 9. 4.3Inner' block rotation 180 degrees 94"Inner block rotation 90 degrees clockwise 9.4.5"Outer" block rotation 90 degrees counterclockwise 9.4.6"" block rotation 180 degrees 9. 4.7"Outer" block rotation 90 degrees clockwise 9.5 Blocktransposing a 2D matrix 9.5. 1"Inner" blocktransposing 9.5.2"Outer blocktransposing 10 Basic arithmetic operations ply arrays 10. 1. 1 Multiply each 2D slice with the same matrix(element-by-element) 10.1.2 Multiply each 2D slice with the same matrix(left) 10.1.3 Multiply each 2D slice with the same matrix(right) 10.1.4 Multiply matrix with every element of a vector 10.1.5 Multiply each 2D slice with corresponding element of a vector 10.1.6 Outer product of all rows in a matrix 10. 1.7 Keeping only diagonal elements of multiplication 32 0. 1.8 Products involving the Kronecker product 10.2 Divide arrays 10.2. 1 Divide each 2D slice with the same matrix(element-by-element) 10.2.2 Divide each 2D slice with the same matrix(left) 10.2. 3 Divide each 2D slice with the same matrix(right)
CONTENTS iii 7 Replicating elements and arrays 13 7.1 Creating a constant array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 7.2 Replicating elements in vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 7.2.1 Replicate each element a constant number of times . . . . . . . . . . . . . . 13 7.2.2 Replicate each element a variable number of times . . . . . . . . . . . . . . 13 7.3 Using KRON for replicating elements . . . . . . . . . . . . . . . . . . . . . . . . . 14 7.3.1 KRON with an matrix of ones . . . . . . . . . . . . . . . . . . . . . . . . . 14 7.3.2 KRON with an identity matrix . . . . . . . . . . . . . . . . . . . . . . . . . 14 8 Reshaping arrays 16 8.1 Subdividing 2D matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 8.1.1 Create 4D array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 8.1.2 Create 3D array (columns first) . . . . . . . . . . . . . . . . . . . . . . . . . 16 8.1.3 Create 3D array (rows first) . . . . . . . . . . . . . . . . . . . . . . . . . . 17 8.1.4 Create 2D matrix (columns first, column output) . . . . . . . . . . . . . . . 17 8.1.5 Create 2D matrix (columns first, row output) . . . . . . . . . . . . . . . . . 18 8.1.6 Create 2D matrix (rows first, column output) . . . . . . . . . . . . . . . . . 18 8.1.7 Create 2D matrix (rows first, row output) . . . . . . . . . . . . . . . . . . . 19 8.2 Stacking and unstacking pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 9 Rotating matrices and arrays 20 9.1 Rotating 2D matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 9.2 Rotating ND arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 9.3 Rotating ND arrays around an arbitrary axis . . . . . . . . . . . . . . . . . . . . . . 21 9.4 Block-rotating 2D matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 9.4.1 “Inner” vs “outer” block rotation . . . . . . . . . . . . . . . . . . . . . . . . 22 9.4.2 “Inner” block rotation 90 degrees counterclockwise . . . . . . . . . . . . . . 23 9.4.3 “Inner” block rotation 180 degrees . . . . . . . . . . . . . . . . . . . . . . . 24 9.4.4 “Inner” block rotation 90 degrees clockwise . . . . . . . . . . . . . . . . . . 25 9.4.5 “Outer” block rotation 90 degrees counterclockwise . . . . . . . . . . . . . 26 9.4.6 “Outer” block rotation 180 degrees . . . . . . . . . . . . . . . . . . . . . . 27 9.4.7 “Outer” block rotation 90 degrees clockwise . . . . . . . . . . . . . . . . . 28 9.5 Blocktransposing a 2D matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 9.5.1 “Inner” blocktransposing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 9.5.2 “Outer” blocktransposing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 10 Basic arithmetic operations 30 10.1 Multiply arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 10.1.1 Multiply each 2D slice with the same matrix (element-by-element) . . . . . . 30 10.1.2 Multiply each 2D slice with the same matrix (left) . . . . . . . . . . . . . . 30 10.1.3 Multiply each 2D slice with the same matrix (right) . . . . . . . . . . . . . . 30 10.1.4 Multiply matrix with every element of a vector . . . . . . . . . . . . . . . . 31 10.1.5 Multiply each 2D slice with corresponding element of a vector . . . . . . . . 32 10.1.6 Outer product of all rows in a matrix . . . . . . . . . . . . . . . . . . . . . . 32 10.1.7 Keeping only diagonal elements of multiplication . . . . . . . . . . . . . . . 32 10.1.8 Products involving the Kronecker product . . . . . . . . . . . . . . . . . . . 33 10.2 Divide arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 10.2.1 Divide each 2D slice with the same matrix (element-by-element) . . . . . . . 33 10.2.2 Divide each 2D slice with the same matrix (left) . . . . . . . . . . . . . . . . 33 10.2.3 Divide each 2D slice with the same matrix (right) . . . . . . . . . . . . . . . 34
CONTENTS 11 More complicated arithmetic operations 11.1 Calculating distances 11.1.1 Euclidean distance 11.1.2 Distance between two points 11.1.3 Euclidean distance vector 11.14 Euclidean distance matrix 11.1.5 Special case when both matrices are identical 11.16 Mahalanobis distance 12 Statistics, probability and combinatorics 12. 1 Discrete uniform sampling with replacement 12.2 Discrete weighted sampling with replacement 12.3 Discrete uniform sampling without replacement 12.4 Combinations 12.4.1 Counting combination 12.4.2 Generating 12.5 Permutations 5.1 Counting permutations 12.5.2 Generating permutations 13 Identifying types of arrays 13.1 Numeric array 13.2 Real array 13.3 Identify real or purely imaginary elements 13.4 Array of negative, non-negative or positive values 13.5 Array of integers 13.6 Scalar 13. 7 Vector 13.8 Matrix 13.9 Array slice 14 Logical operators and comparisons 14.1 List of logical operators 14.2 Rules for logical operators 44 14.3 Quick tests before slow ones 15 Miscellaneous 15.1 Accessing elements on the dia 46 15.2 Creating index vector from index limits 47 15.3 Matrix with different incremental runs 15.4 Finding indices 15.4.1 First non-zero element in each column 15.4.2 First non-zero element in each row 15.4.3 Last non-zero element in each row 15.5 Run-length encoding and decoding 15.5.1 Run-length ene 5.6 Counting bi
CONTENTS iv 11 More complicated arithmetic operations 35 11.1 Calculating distances . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 11.1.1 Euclidean distance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 11.1.2 Distance between two points . . . . . . . . . . . . . . . . . . . . . . . . . . 35 11.1.3 Euclidean distance vector . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 11.1.4 Euclidean distance matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 11.1.5 Special case when both matrices are identical . . . . . . . . . . . . . . . . . 36 11.1.6 Mahalanobis distance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 12 Statistics, probability and combinatorics 38 12.1 Discrete uniform sampling with replacement . . . . . . . . . . . . . . . . . . . . . . 38 12.2 Discrete weighted sampling with replacement . . . . . . . . . . . . . . . . . . . . . 38 12.3 Discrete uniform sampling without replacement . . . . . . . . . . . . . . . . . . . . 38 12.4 Combinations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 12.4.1 Counting combinations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 12.4.2 Generating combinations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 12.5 Permutations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 12.5.1 Counting permutations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 12.5.2 Generating permutations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 13 Identifying types of arrays 41 13.1 Numeric array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 13.2 Real array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 13.3 Identify real or purely imaginary elements . . . . . . . . . . . . . . . . . . . . . . . 42 13.4 Array of negative, non-negative or positive values . . . . . . . . . . . . . . . . . . . 42 13.5 Array of integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 13.6 Scalar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 13.7 Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 13.8 Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 13.9 Array slice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 14 Logical operators and comparisons 44 14.1 List of logical operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 14.2 Rules for logical operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 14.3 Quick tests before slow ones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 15 Miscellaneous 46 15.1 Accessing elements on the diagonal . . . . . . . . . . . . . . . . . . . . . . . . . . 46 15.2 Creating index vector from index limits . . . . . . . . . . . . . . . . . . . . . . . . 47 15.3 Matrix with different incremental runs . . . . . . . . . . . . . . . . . . . . . . . . . 48 15.4 Finding indices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 15.4.1 First non-zero element in each column . . . . . . . . . . . . . . . . . . . . . 48 15.4.2 First non-zero element in each row . . . . . . . . . . . . . . . . . . . . . . . 49 15.4.3 Last non-zero element in each row . . . . . . . . . . . . . . . . . . . . . . . 50 15.5 Run-length encoding and decoding . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 15.5.1 Run-length encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 15.5.2 Run-length decoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 15.6 Counting bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
CONTENTS Appendix A MATLAB resourees
CONTENTS v Appendix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 A M A T L A B resources 55
Preface The essence This document is intended to be a compilation of tips and tricks mainly related to efficient ways of manipulating arrays in MATLAB. Here, "manipulating arrays"includes replicating and rotating arrays or parts of arrays, inserting, extracting, replacing, permuting and shifting arrays or parts of arrays, generating combinations and permutations of elements, run-length encoding and decoding, arithmetic operations like multiplying and dividing arrays, calculating distance matrices and more A few other issues related to writing fast MATLAB code are also covered I want to thank Ken Doniger, Dr. Denis Gilbert for their contributions, suggestions, and cor- Why i wrote this Since the early 1990s I have been following the discussions in the main MATLAB newsgroup on Usenet, comp. soft-sys. matlab. I realized that many of the postings in the group were about how to manipulate arrays efficiently, which was something I had a great interest in. Since many of the same questions appeared again and again, I decided to start collecting what I thought were the nterestings problems and solutions and see if I could compile them into one document. That Intended audience This document is mainly intended for those of you who already know the basics of MATLAB and would like to dig further into the material regarding manipulating arrays efficiently How to read this This document is more of a reference than a tutorial. Although it might be read from beginning to end, the best way to use it is probably to get familiar with what is covered and then look it up here when you bump into a problem which is covered here The language is rather technical al though many of the terms used are explained. The index at the back should be an aid in finding the explanation for a term unfamiliar to you
Preface The essence This document is intended to be a compilation of tips and tricks mainly related to efficient ways of manipulating arrays in MATLAB. Here, “manipulating arrays” includes replicating and rotating arrays or parts of arrays, inserting, extracting, replacing, permuting and shifting arrays or parts of arrays, generating combinations and permutations of elements, run-length encoding and decoding, arithmetic operations like multiplying and dividing arrays, calculating distance matrices and more. A few other issues related to writing fast MATLAB code are also covered. I want to thank Ken Doniger, Dr. Denis Gilbert for their contributions, suggestions, and corrections. Why I wrote this Since the early 1990’s I have been following the discussions in the main MATLAB newsgroup on Usenet, comp.soft-sys.matlab. I realized that many of the postings in the group were about how to manipulate arrays efficiently, which was something I had a great interest in. Since many of the same questions appeared again and again, I decided to start collecting what I thought were the most interestings problems and solutions and see if I could compile them into one document. That was the beginning of what you are now reading. Intended audience This document is mainly intended for those of you who already know the basics of MATLAB and would like to dig further into the material regarding manipulating arrays efficiently. How to read this This document is more of a reference than a tutorial. Although it might be read from beginning to end, the best way to use it is probably to get familiar with what is covered and then look it up here when you bump into a problem which is covered here. The language is rather technical although many of the terms used are explained. The index at the back should be an aid in finding the explanation for a term unfamiliar to you. vi
CONTENTS Organization problen and attempt ing a compilation of questions and answers, I have organized the material into Instead of just provi to give general answers, where possible. That way, a solution for a particular oesn't just answer that one problem, but rather, that problem and all similar problems Many of the sections start off with a general description of what the section is about and what kind of problems that are solved there. Following that are implementations which may be used to solve the given problem Typographical conversions All MATLAB code is set in a monospaced font, like this, and the rest is set in a proportional font. En ellipsis(... )is sometimes used to indicated omitted code. It should be apparent from the context whether the ellipsis is used to indicate omitted code or if the ellipsis is the line continuation ymbol used in MATLAB MATLAB functions are, like other MATLAB code, set in a proportional font, but in addition, the text is hyperlinked to the documentation pages at The Math Works web site. Thus, depending on the pdf document reader, clicking the function name will open a web browser window showing the appropriate documentation page Credits To the extent possible, I have given credit to what I believe is the author of a particular solution. In many cases there is no single author, since several people have been tweaking and trimming each other's solutions. If I have given credit to the wrong person, please let me know. In particular, I do not claim to be the sole author of a solution even when there is no other mentioned Errors and feedback If you find errors, or have suggestions for improvements, or if there is anything you think should be here but is not, please mail me and I will see what I can do. My address is on the front page of this do
CONTENTS vii Organization Instead of just providing a compilation of questions and answers, I have organized the material into sections and attempted to give general answers, where possible. That way, a solution for a particular problem doesn’t just answer that one problem, but rather, that problem and all similar problems. Many of the sections start off with a general description of what the section is about and what kind of problems that are solved there. Following that are implementations which may be used to solve the given problem. Typographical convensions All MATLAB code is set in a monospaced font, like this, and the rest is set in a proportional font. En ellipsis (...) is sometimes used to indicated omitted code. It should be apparent from the context whether the ellipsis is used to indicate omitted code or if the ellipsis is the line continuation symbol used in MATLAB. MATLAB functions are, like other MATLAB code, set in a proportional font, but in addition, the text is hyperlinked to the documentation pages at The MathWorks’ web site. Thus, depending on the PDF document reader, clicking the function name will open a web browser window showing the appropriate documentation page. Credits To the extent possible, I have given credit to what I believe is the author of a particular solution. In many cases there is no single author, since several people have been tweaking and trimming each other’s solutions. If I have given credit to the wrong person, please let me know. In particular, I do not claim to be the sole author of a solution even when there is no other name mentioned. Errors and feedback If you find errors, or have suggestions for improvements, or if there is anything you think should be here but is not, please mail me and I will see what I can do. My address is on the front page of this document
Chapter 1 High-level vs low-level code 1.1 Introduction Like other computer languages, MATLAB provides operators and functions for creating and mani- pulating arrays. Arrays may be manipulated one element at a time, like one does in low-level lan- guages. Since MATLAB is a high-level programming language it also provides high-level operator and functions for manipulating arrays Any task which can be done in MATLAB with high-level constructs may also be done with low- level constructs. Here is an example of a low-level way of squaring the elements of a vector x=[12345 s vector of value square (size(x)) for i= 1: numel(x) s for each index y(i)=x(i)^2 号 square the value nd here is the high-level, or"vectorized, way of doing the same x=[12345]; f value 8 square all the values The use of the higher-level operator makes the code more compact and more easy to read, but this is not al ways the case. Before you start using high-level functions extensively, you ought to consider advantages and disadvantages 1.2 Advantages and disadvantages It is not always easy to decide when to use low-level functions and when to use high-level functions There are advantages and disadvantages with both. Before you decide what to use, consider the following advantages and disadvantages with low-level and high-level code 1. 2.1 Portability Low-level code looks much the same in most programming languages. Thus, someone who is used to writing low-level code in some other language will quite easily be able to do the same in MATLaB And vice versa, low-level MATLAB code is more easily ported to other languages than high-level MATLAB code
Chapter 1 High-level vs low-level code 1.1 Introduction Like other computer languages, MATLAB provides operators and functions for creating and manipulating arrays. Arrays may be manipulated one element at a time, like one does in low-level languages. Since MATLAB is a high-level programming language it also provides high-level operators and functions for manipulating arrays. Any task which can be done in MATLAB with high-level constructs may also be done with lowlevel constructs. Here is an example of a low-level way of squaring the elements of a vector x = [ 1 2 3 4 5 ]; % vector of values to square y = zeros(size(x)); % initialize new vector for i = 1 : numel(x) % for each index y(i) = x(i)^2; % square the value end % end of loop and here is the high-level, or “vectorized”, way of doing the same x = [ 1 2 3 4 5 ]; % vector of values to square y = x.^2; % square all the values The use of the higher-level operator makes the code more compact and more easy to read, but this is not always the case. Before you start using high-level functions extensively, you ought to consider the advantages and disadvantages. 1.2 Advantages and disadvantages It is not always easy to decide when to use low-level functions and when to use high-level functions. There are advantages and disadvantages with both. Before you decide what to use, consider the following advantages and disadvantages with low-level and high-level code. 1.2.1 Portability Low-level code looks much the same in most programming languages. Thus, someone who is used to writing low-level code in some other language will quite easily be able to do the same in MATLAB. And vice versa, low-level MATLAB code is more easily ported to other languages than high-level MATLAB code. 1
CHAPTER I. HIGH-LEVEL VS LOW-LEVEL CODE 1. 2. 2 Verbosity The whole purpose of a high-level function is to do more than the low-level equivalent. Thus, using high-level functions results in more compact code. Compact code requires less coding, and generally, the less you have to write the less likely it is that you make a mistake. Also, isis more easy to get an overview of compact code; having to wade through vast amounts of code makes it 1. 2.3 Speed Traditionally, low-level MATLAB code ran more slowly than high-level code, so among MATLAB users there has always been a great desire to speed up execution by replacing low-level code with high-level code. This is clearly seen in the MATLAB newsgroup on Usenet, comp. soft-sys matlab where many postings are about how to"translate"a low-level construction into the high-level equi- valent In matlab6.5 an accelerator was introduced. The accelerator makes low-level code run much faster. At this time, not all code will be accelerated, but the accelerator is still under development and it is likely that more code will be accelerated in future releases of MATLAB. The MATLAB documentation contains specific information about what code is accelerated 1. 2. 4 Obscurit High-level code is more compact than low-level code, but sometimes the code is so compact that is it has become quite obscure. Although it might impress someone that a lot can be done with a minimum code, it is a nightmare to maintain undocumented high-level code. You should always document your code, and this is even more important if your extensive use of high-level code makes he code obscure 1.2.5 Difficulty Writing efficient high-level code requires a different way of thinking than writing low-level code. It requires a higher level of abstraction which some people find difficult to master. As with everything else in life, if you want to be good at it, you must practice 1.3 Words of warning Don't waste your time. Dont rewrite code which doesnt need rewriting. Don' t optimize code before you are certain that the code is a bottleneck. Even if the code is a bottleneck: Dont spend two hours reducing the execution time of your program by one minute unless you are going to run the program so many times that you will save the two hours you spent optimizing it in the first place
CHAPTER 1. HIGH-LEVEL VS LOW-LEVEL CODE 2 1.2.2 Verbosity The whole purpose of a high-level function is to do more than the low-level equivalent. Thus, using high-level functions results in more compact code. Compact code requires less coding, and generally, the less you have to write the less likely it is that you make a mistake. Also, is is more easy to get an overview of compact code; having to wade through vast amounts of code makes it more easy to lose the big picture. 1.2.3 Speed Traditionally, low-level MATLAB code ran more slowly than high-level code, so among MATLAB users there has always been a great desire to speed up execution by replacing low-level code with high-level code. This is clearly seen in the MATLAB newsgroup on Usenet, comp.soft-sys.matlab, where many postings are about how to “translate” a low-level construction into the high-level equivalent. In MATLAB 6.5 an accelerator was introduced. The accelerator makes low-level code run much faster. At this time, not all code will be accelerated, but the accelerator is still under development and it is likely that more code will be accelerated in future releases of MATLAB. The MATLAB documentation contains specific information about what code is accelerated. 1.2.4 Obscurity High-level code is more compact than low-level code, but sometimes the code is so compact that is it has become quite obscure. Although it might impress someone that a lot can be done with a minimum code, it is a nightmare to maintain undocumented high-level code. You should always document your code, and this is even more important if your extensive use of high-level code makes the code obscure. 1.2.5 Difficulty Writing efficient high-level code requires a different way of thinking than writing low-level code. It requires a higher level of abstraction which some people find difficult to master. As with everything else in life, if you want to be good at it, you must practice. 1.3 Words of warning Don’t waste your time. Don’t rewrite code which doesn’t need rewriting. Don’t optimize code before you are certain that the code is a bottleneck. Even if the code is a bottleneck: Don’t spend two hours reducing the execution time of your program by one minute unless you are going to run the program so many times that you will save the two hours you spent optimizing it in the first place
Chapter 2 Operators, functions and special characters Clearly, it is important to know the language you intend to use. The language is described in the manuals so I won't repeat what they say, but I encourage you to type help ops help relop help arith help slash at the command prompt and take a look at the list of operators, functions and special characters, and look at the associated help pages When manipulating arrays in MATLAB there are some operators and functions that are partic rarely 2.1 Operators In addition to the arithmetic operators, MATLAB provides a couple of other useful operators The colon operator Type help colon for more information Non-conjugate transpose Type help transpose for more information Complex conjugate transpose Type help transpose for more information
Chapter 2 Operators, functions and special characters Clearly, it is important to know the language you intend to use. The language is described in the manuals so I won’t repeat what they say, but I encourage you to type help ops help relop help arith help slash at the command prompt and take a look at the list of operators, functions and special characters, and look at the associated help pages. When manipulating arrays in MATLAB there are some operators and functions that are particularely useful. 2.1 Operators In addition to the arithmetic operators, MATLAB provides a couple of other useful operators : The colon operator. Type help colon for more information. .’ Non-conjugate transpose. Type help transpose for more information. ’ Complex conjugate transpose. Type help ctranspose for more information. 3