33
CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

Embed Size (px)

Citation preview

Page 1: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

1

CS 598 Scripting Languages Design and Implementation

2. MATLAB

Page 2: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

2

Origins

• Designed by Cleve Moler in the late 1970s.

• It is mainly his design and in fact the MATLAB logo is from his 1965 PhD Thesis (see right)

• Initial version seems to have been mainly a FORTRAN-like simple interface to LINPACK and EISPACK.

• Has become immensely popular• See

http://www.mathworks.com/company/newsletters/articles/the-origins-of-matlab.html

Page 3: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

3

Environment

• It is and interactive environment.• With a number of nice features• It is free from the CITES Webstore• .m files hold your code.– Use edit name in the command line to create a

new script (stored in a file called name.m)

Page 4: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

4

Interactive MATLAB

• Can be used as a graphing calculator.• For example:

x=-6.28:1:6.28; % a vector of values % -6.28+i*1 with i>=0 % and -6.28+i*1<=6.28 plot(x,sin(x))– Will produce a (bad) plot of the function sin.– Refining x to steps of .01 improves the graph

Page 5: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

5

Variables

• ~ like FORTRAN• Reserved variable names– i and j are sqrt(-1)– pi is 3.1415926…– ans is last value– Inf is ∞– NaN is ‘Not a Number’

Page 6: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

6

Dynamic typing

• Type of variables can change dynamically.• Sometime with unintended consequences.

E.g. what is the output of for kk=1:10 w=2*i i=kk; end ?

Page 7: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

7

Classes of objects

S = class(OBJ) returns the name of the class of object OBJ. Possibilities are:• double -- Double precision floating point number array• (this is the traditional MATLAB matrix or array)• single -- Single precision floating point number array• logical -- Logical array• char -- Character array• cell -- Cell array• struct -- Structure array

Page 8: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

8

• function_handle -- Function Handle– x=@sin % class(x) is function_handle

• int8 -- 8-bit signed integer array• uint8 -- 8-bit unsigned integer array• int16 -- 16-bit signed integer array• uint16 -- 16-bit unsigned integer array• int32 -- 32-bit signed integer array• uint32 -- 32-bit unsigned integer array• int64 -- 64-bit signed integer array• uint64 -- 64-bit unsigned integer array• <class_name> -- MATLAB class name for MATLAB objects• <java_class> -- Java class name for java objects

Page 9: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

9

Arrays

• Two classes:– Regular arrays– Cell arrays

• Variables are matrices by default– scalars are typically 1 × 1 arrays

• size is a vector containing the size of each dimension

• length(x) is max(size(x))

Page 10: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

10

Arrays

• Constant arrays are list of values within brackets.

• Comma (,)of space separates elements of a row.

• Semicolon (;) separates rows.• Arrays of more than two dimensions cannot

be represented as constants

Page 11: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

11

Array size

• Array sizes are not fixed but dynamic• Thus, if a had not been assigned before, a(1,2)=3 will create the array a with value [0 3] and then a(1,8)=4 will expand a to [ 0 3 0 0 0 0 0 4 ]

• To avoid the cost of resizing at each assignments, the array can be initialized using functions lie zeros and ones

Page 12: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

12

Expressions

• Arithmetic operations and intrinsic functions similar to FORTRAN.

• Typically extended to arrays to operate on an element by element basis.– Exception: for *, / and ^(exponentiation) use .*, ./,

and .^ for element by element operations.• Binary operators must work on conformable

operands – Arrays that have the same size (including pairs of scalars.– One array and one scalar.

Page 13: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

13

Expressions

• * is Matrix matrix multiplication• / is matrix division (a/b is a*inv(b))• \ has a similar meaning (a\b is inv(a)*b)• ^ is matrix exponentiation (a^2 is a*a)

Page 14: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

14

Accessing array elements

• Use scalars,– a(2,3)

• triplet notation,– a(init:step:end) are the a(k) where k

is an element of the vector init:step:end– init, step and end are optional default to 1, 1 and length(a) respectively.

• or a combination of these.– a(3, 5:7, 6:3, 4)

Page 15: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

15

Assigning arrays

• Array assignment statement, the right hand side is evaluated before any value is assigned. E.g. how much faster will the assignment a=zeros make the loop?

% a=zeros(1,1000000); tic for i=1:1000000 a(i)=0; end toc

Page 16: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

16

Functions

Page 17: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

17

Input parameter passing

• Parameters are typically passed by value.• The parameter passing is implemented using

copy-on-write strategy.

Page 18: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

18

Flow of control

if cond command end

if cond command else command end

if cond command elseif cond command … else command end

Page 19: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

19

Flow of control

• There are also for loops and while loops for n=1:20 commands end

while cond commands end

Page 20: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

20

Cell arrays

• Can have heterogeneous elements• Access using curly brackets– a=cell(2,3)– a{1,2}=‘this is a string’– a{2,3}=5

• Can use triplets and array operations such as transpose.

Page 21: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

21

Structs

• Can be created using struct– c=struct('a',1)

• And entries can be added dynamically– c.b=3

Page 22: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

22

Classes

• MATLAB classes are defined using classdef• Subclasses• Abstract classes• And privacy control

• It is possible to dynamically add properties to an instance.– Use addprop for instance of objects whose class is a subclass

of dynamicprops

Page 23: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

23

Classes

classdef orderednode < handleproperties idendproperties (SetAccess = private) prev nextendmethods function node = orderednode(n) node.id = 0; if nargin > 0 node.id = n; end end function disp(node) if isscalar(node) if ~isempty(node.id) disp(node.id); end disp(node.next); else disp('Array of nodes'); end end function t = gt(a,b) t = (a.id > b.id); end

function insert(node, head) if isempty(head) error('no list provided'); end cur = head; last = []; while ~isempty(cur) && node > cur last = cur; cur = cur.next; end if node == cur error('Node already in the list'); end if isempty(last) node.next = head; node.prev = []; head.prev = node; else last.next = node; node.prev = last; node.next = cur; if ~isempty(cur) cur.prev = node; end end endendend

classnamesubclass

privacy

Overloading ‘>’

Page 24: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

24

Classes of classes

• A value class constructor returns an instance that is associated with the variable to which it is assigned. If you reassign this variable, MATLAB® creates a copy of the original object. If you pass this variable to a function, the function must return the modified object.

• A handle class constructor returns a handle object that is a reference to the object created. You can assign the handle object to multiple variables or pass it to functions without causing MATLAB to make a copy of the original object. A function that modifies a handle object passed as an input argument does not need to return the object.

Page 25: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

25

Using MATLAB as glue code

• Calling C from MATLAB is “easy”• Use MEX files

Page 26: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

26

MEX Files/*=============================================

• arrayProduct.c - example in MATLAB External Interfaces * * Multiplies an input scalar (multiplier) * times a 1xN matrix (inMatrix) * and outputs a 1xN matrix (outMatrix) * * The calling syntax is: * * outMatrix = arrayProduct(multiplier, inMatrix) * * This is a MEX-file for MATLAB. * Copyright 2007-2010 The MathWorks, Inc. * *================================================*//* $Revision: 1.1.10.3 $ */

#include "mex.h/* The computational routine */void arrayProduct(double x, double *y, double *z, mwSize n){ mwSize i; /* multiply each element y by x */ for (i=0; i<n; i++) { z[i] = x * y[i]; }} }

/* The gateway function */void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ double multiplier; /* input scalar */ double *inMatrix; /* 1xN input matrix */ size_t ncols; /* size of matrix */ double *outMatrix; /* output matrix */

/* check for proper number of arguments */ if(nrhs!=2) { mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs", "Two inputs required."); } if(nlhs!=1) { mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nlhs", "One output required."); } /* make sure the first input argument is scalar*/ if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || mxGetNumberOfElements(prhs[0])!=1 ) { mexErrMsgIdAndTxt( "MyToolbox:arrayProduct:notScalar", "Input multiplier must be a scalar."); }

Page 27: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

27

MEX Files cont/* check that number of rows in second input argument is 1 */ if(mxGetM(prhs[1])!=1) { mexErrMsgIdAndTxt("MyToolbox:arrayProduct:notRowVector","Input must be a row vector."); } /* get the value of the scalar input */ multiplier = mxGetScalar(prhs[0]);

/* create a pointer to the real data in the input matrix */ inMatrix = mxGetPr(prhs[1]);

/* get dimensions of the input matrix */ ncols = mxGetN(prhs[1]);

/* create the output matrix */ plhs[0] = mxCreateDoubleMatrix(1,(mwSize)ncols,mxREAL);

/* get a pointer to the real data in the output matrix */ outMatrix = mxGetPr(plhs[0]);

/* call the computational routine */ arrayProduct(multiplier,inMatrix,outMatrix,(mwSize)ncols);}

s = 5; A = [1.5, 2, 9];B = arrayProduct(s,A)

Page 28: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

28

HIERARCHICALLY TILED ARRAYS

Page 29: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

29

Array operations for parallelism

• Array operations are a great example of abstractions for parallel programming. – Can be implemented sequentially and in parallel.– Given two arrays, A and B, A*B can represent

either dense or sparse computations

Page 30: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

30

Array operations for programmability

Matrix addition in scalar mode

for i=1:m, for j=1:l,

c(i,j)= a(i,j) + b(i,j); endend

Matrix addition in array notation is simpler

c = a + b;

Page 31: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

31

An important generalization:Hierarchically Tiled Arrays

• Recognizes the importance of blocking/tiling for locality and parallel programming.

• Makes tiles first class objects. – Referenced explicitly. – Manipulated using array operations

such as reductions, gather, etc..

Page 32: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

32

Locality

Locality

Distributed

A hierarchically tiled array

Ganesh Bikshandi, Jia Guo, Daniel Hoeflinger, Gheorghe Almasi, Basilio B. Fraguela, María J.Garzarán, David Padua, and Christoph von Praun. 2006. Programming for parallelism and locality with hierarchically tiled arrays. In Proceedings of the eleventh ACM SIGPLAN symposium on Principles and practice of parallel programming (PPoPP '06). ACM, New York,NY, USA, 48-57.

Page 33: CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

33

An Example: Summa

T2{:,:}

B

T1{:,:}*

function C = summa (A, B, C)for k=1:m

T1 = repmat(A{:, k}, 1, m); T2 = repmat(B{k, :}, m, 1); C = C + T1{:,:} * T2 {:,:};end

repmat

repmat

broadcast

parallel computation