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

Slides:



Advertisements
Similar presentations
Anthony Delprete Jason Mckean Ryan Pineres Chris Olszewski.
Advertisements

Overview of programming in C C is a fast, efficient, flexible programming language Paradigm: C is procedural (like Fortran, Pascal), not object oriented.
Introduction to Matlab
Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
Kernighan/Ritchie: Kelley/Pohl:
Chapter 10 Introduction to Arrays
 2005 Pearson Education, Inc. All rights reserved Introduction.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05
Introduction to MATLAB Northeastern University: College of Computer and Information Science Co-op Preparation University (CPU) 10/22/2003.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Chapter 8 Arrays and Strings
C ENTER FOR I NTEGRATED R ESEARCH C OMPUTING MATLAB
Introduction to MATLAB MECH 300H Spring Starting of MATLAB.
Chapter 15: Operator Overloading
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Operator Overloading in C++
Basic Elements of C++ Chapter 2.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Imperative Programming
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
Lists in Python.
Mex. Introduction to MEX MEX = Matlab EXecutable – Dynamically Linked Libraries – Used like a.m function – Written in C (or Fortran)
CSE123 Lecture 5 Arrays and Array Operations. Definitions Scalars: Variables that represent single numbers. Note that complex numbers are also scalars,
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
Representing numbers and Basic MATLAB 1. Representing numbers  numbers used by computers do not behave the same as numbers used in mathematics  e.g.,
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Copyright Curt Hill Variables What are they? Why do we need them?
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics Lecture 5.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
Introduction to C and CMex E177 April 1, Copyright , Andy Packard. This work is licensed under the.
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CSI 3125, Preliminaries, page 1 Data Type, Variables.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
INTRODUCTION TO MATLAB Dr. Hugh Blanton ENTC 4347.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Introduction to CMex E177 April 25, Copyright 2005, Andy Packard. This work is licensed under the Creative.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
1 ENERGY 211 / CME 211 Lecture 4 September 29, 2008.
Introduction to Algorithmic Processes CMPSC 201C Fall 2000.
Reflections on Dynamic Languages and Parallelism David Padua University of Illinois at Urbana-Champaign 1.
Definition of the Programming Language CPRL
A bit of C programming Lecture 3 Uli Raich.
BASIC ELEMENTS OF A COMPUTER PROGRAM
Java Primer 1: Types, Classes and Operators
L – Modeling and Simulating Social Systems with MATLAB
MatLab Programming By Kishan Kathiriya.
Matlab Workshop 9/22/2018.
Introduction C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell.
Introduction to Matlab
Python Primer 1: Types and Operators
INTRODUCTION TO MATLAB
Introduction to MATLAB
7 Arrays.
Matlab Basics.
ENERGY 211 / CME 211 Lecture 28 December 1, 2008.
Presentation transcript:

CS 598 Scripting Languages Design and Implementation 2. MATLAB 1

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 ny/newsletters/articles/the-origins- of-matlab.html ny/newsletters/articles/the-origins- of-matlab.html 2

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 ) 3

Interactive MATLAB Can be used as a graphing calculator. For example: x=-6.28:1:6.28; % a vector of values % i *1 with i>=0 % and 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 4

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

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 ? 6

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 7

function_handle -- Function Handle – % class(x) is function_handle int bit signed integer array uint bit unsigned integer array int bit signed integer array uint bit unsigned integer array int bit signed integer array uint bit unsigned integer array int bit signed integer array uint bit unsigned integer array -- MATLAB class name for MATLAB objects -- Java class name for java objects 8

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)) 9

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 10

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 [ ] To avoid the cost of resizing at each assignments, the array can be initialized using functions lie zeros and ones 11

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. 12

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 ) 13

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) 14

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, ); tic for i=1: a(i)=0; end toc 15

Functions 16

Input parameter passing Parameters are typically passed by value. The parameter passing is implemented using copy-on-write strategy. 17

Flow of control if cond command end if cond command else command end 18 if cond command elseif cond command … else command end

Flow of control There are also for loops and while loops for n=1:20 commands end while cond commands end 19

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. 20

Structs Can be created using struct – c=struct('a',1) And entries can be added dynamically – c.b=3 21

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 22

Classes classdef orderednode < handle properties id end properties (SetAccess = private) prev next end methods 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 function t = gt(a,b) t = (a.id > b.id); end 23 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 classname subclass privacy Overloading ‘>’

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. 24

Using MATLAB as glue code Calling C from MATLAB is “easy” Use MEX files 25

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 The MathWorks, Inc. * *================================================*/ /* $Revision: $ */ #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."); } 26

MEX Files cont /* check that number of rows in second input argument is 1 */ if(mxGetM(prhs[1])!=1) { mexErrMsgIdAndTxt("MyToolbox:arrayProduct:notRowV ector","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,(mwSiz e)ncols); } 27 s = 5; A = [1.5, 2, 9]; B = arrayProduct(s,A)

HIERARCHICALLY TILED ARRAYS 28

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 29

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); end Matrix addition in array notation is simpler c = a + b; 30

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.. 31

Locality Distributed A hierarchically tiled array 32 Ganesh Bikshandi, Jia Guo, Daniel Hoeflinger, Gheorghe Almasi, Basilio B. Fraguela, María J. Garzarán, David Padua, and Christoph von Praun 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,

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 broadcast parallel computation 33