ME451 Kinematics and Dynamics of Machine Systems MATLAB  Tutorial September 16, 2014 Dan Negrut University of Wisconsin-Madison 1.

Slides:



Advertisements
Similar presentations
Lecture 5.
Advertisements

Introduction to M ATLAB Programming Ian Brooks Institute for Climate & Atmospheric Science School of Earth & Environment
Introduction to Matlab
AMS597 Spring 2011 Hao Han April 05, Introduction to MATLAB The name MATLAB stands for MATrix LABoratory. Typical uses include:  Math and computation.
Introduction to Matlab Workshop Matthew Johnson, Economics October 17, /13/20151.
MATLAB – What is it? Computing environment / programming language Tool for manipulating matrices Many applications, you just need to get some numbers in.
Introduction to Matlab By: Dr. Maher O. EL-Ghossain.
EGR 106 – Week 2 – Arrays Definition, size, and terminology Construction methods Addressing and sub-arrays Some useful functions for arrays Character arrays.
EGR 106 – Week 2 – Arrays & Scripts Brief review of last week Arrays: – Concept – Construction – Addressing Scripts and the editor Audio arrays Textbook.
Introduction to MATLAB Northeastern University: College of Computer and Information Science Co-op Preparation University (CPU) 10/29/2003.
EGR 105 Foundations of Engineering I Session 3 Excel – Basics through Graphing Fall 2008.
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.
What is MATLAB ? MATrix LABratory –Originally, it was a front-end to FORTRAN matrix routines developed in the U. of New Mexico and Stanford –Today.
Signals and Systems Laboratory 2013 Teacher: Marek OssowskiTeacher: Marek Ossowski Phone: , Room 14, C3,
1 Prof. Nizamettin AYDIN Biosignals and Systems.
Chapter 10 Review: Matrix Algebra
MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command.
MATLAB Lecture One Monday 4 July Matlab Melvyn Sim Department of Decision Sciences NUS Business School
MATLAB INTRO CONTROL LAB1  The Environment  The command prompt Getting Help : e.g help sin, lookfor cos Variables Vectors, Matrices, and Linear Algebra.
M ATLAB Tutorial Course 1. Contents Continued  Desktop tools  matrices  Logical &Mathematical operations  Handle Graphics  Ordinary Differential.
Nonparametric Econometrics1 Intro to Matlab for Data Analysis and Statistical Modeling.
1 M ATLAB Short Course. History of Calculator 2 3 Introduction to Matlab Matlab is short for Matrix Laboratory Matlab is also a programming language.
Introduction to MATLAB Session 1 Prepared By: Dina El Kholy Ahmed Dalal Statistics Course – Biomedical Department -year 3.
Introduction to Matlab 1. Outline: What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators Plotting Flow Control Using of M-File Writing.
Introduction to MATLAB
ELG 3120 Signal and System Analysis 1 Introduction to MATLAB TAs Wei Zhang Ozgur Ekici (Section A)(Section B) ELG 3120 Lab Tutorial 1.
Recap Graphic Window Edit Window Start Button Matrices in MATLAB Scalar Operations Order of Operations Array Operations Matrix Addition Matrix Multiplication.
1 Lab of COMP 406 Teaching Assistant: Pei-Yuan Zhou Contact: Lab 1: 12 Sep., 2014 Introduction of Matlab (I)
MEGN 536 – Computational Biomechanics MATLAB: Getting Started Prof. Anthony J. Petrella Computational Biomechanics Group.
A Brief Introduction to Matlab Laila Guessous Dept. of Mechanical Engineering Oakland University.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
MATLAB Tutorial EE 327 Signals and Systems 1. What is MATLAB? MATLAB – Matrix Laboratory The premier number-crunching software Extremely useful for signal.
Eng Ship Structures 1 Introduction to Matlab.
INTRODUCTION TO MATLAB LAB# 01
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (1): Introduction.
Matlab Basics Tutorial. Vectors Let's start off by creating something simple, like a vector. Enter each element of the vector (separated by a space) between.
Matlab Programming for Engineers Dr. Bashir NOURI Introduction to Matlab Matlab Basics Branching Statements Loops User Defined Functions Additional Data.
10/24/20151 Chapter 2 Review: MATLAB Environment Introduction to MATLAB 7 Engineering 161.
1 M ATLAB Short Course Part (2). 2 Elementary Math Function abs, sign: Absolute value and Signum Function sin, cos, asin, acos…: Triangular functions.
Matlab 14.html Cost: $100 Available in labs on Windows and Unix machines.
Introduction to MATLAB Session 1 Simopekka Vänskä, THL 2010.
OUTLINE Overview Numbers, variables and similar in Matlab
Introduction to Matlab. Outline:  What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display.
M ATLAB Tutorial Covered by: Toby Heyn University of Wisconsin, Madison.
INTRODUCTION TO MATLAB MATLAB is a software package for computation in engineering, science, and applied mathemat-ics. It offers a powerful programming.
Matlab Screen  Command Window  type commands  Current Directory  View folders and m-files  Workspace  View program variables  Double click on a.
MATLAB Lecture Two Tuesday 5 July Chapter 3.
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
A Quick Octave Tutorial 阮 翀
Introduction to Matlab
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
INTRODUCTION TO MATLAB Dr. Hugh Blanton ENTC 4347.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
1 Faculty Name Prof. A. A. Saati. 2 MATLAB Fundamentals 3 1.Reading home works ( Applied Numerical Methods )  CHAPTER 2: MATLAB Fundamentals (p.24)
An Introduction to Programming in Matlab Emily Blumenthal
MATLAB (Matrix Algebra laboratory), distributed by The MathWorks, is a technical computing environment for high performance numeric computation and.
Outline What is MATLAB MATLAB desktop Variables, Vectors and Matrices Matrix operations Array operations Built-in functions: Scalar, Vector, Matrix Data.
What is Matlab?  “MATLAB® is a high-level language and interactive environment for numerical computation, visualization, and programming. Using MATLAB,
MATLAB Tutorial Course
Outline Matlab tutorial How to start and exit Matlab Matlab basics.
INTRODUCTION TO BASIC MATLAB
MATLAB DENC 2533 ECADD LAB 9.
Matlab Workshop 9/22/2018.
StatLab Matlab Workshop
StatLab Workshop: Intro to Matlab for Data Analysis and Statistical Modeling 11/29/2018.
Lecture 2 Introduction to MATLAB
Introduction to Matlab
INTRODUCTION TO MATLAB
Matlab Basic Dr. Imtiaz Hussain
Announcements P3 due today
Presentation transcript:

ME451 Kinematics and Dynamics of Machine Systems MATLAB  Tutorial September 16, 2014 Dan Negrut University of Wisconsin-Madison 1

2 Before getting started … Almost entirely, this tutorial was compiled from bits of information gathered from various internet sources Please let me know of any mistakes you find The right frame of mind: You will not be able to say at the end of workshop that you know MATLAB but rather that you have been exposed to MATLAB. Use MATLAB ’ s help – this is your first stop Second stop: search the web for examples that come close to what you need You learn how to use MATLAB by using it, that’s why the start might be slow and at times frustrating 2

3 What is MATLAB? Integrated Development Environment (IDE) Programming Language Collection of Toolboxes A package that excels in Linear Algebra support 3

4 MATLAB as an IDE Integrated development environment (IDE) Write your own code for computation Good visualization (plotting) tools Easy-to-use environment Command Window Command History Help Browser Workspace Browser Editor/Debugger 4

5

6

7 MATLAB as Programming Language High-level language Data types Functions Control flow statements Input/output Graphics Object-oriented programming capabilities 7

8 Toolboxes Collections of functions to solve problems from various application fields: DSP (Digital Signal Processing) Toolbox Image Toolbox Wavelet Toolbox Neural Network Toolbox Fuzzy Logic Toolbox Control Toolbox Multibody Simulation Toolbox And many other … amazing number of toolboxes available: if you need something, it ’ s out there somewhere available for download 8

9 Getting help help command >> help lookfor command >> lookfor Help browser >> doc helpwin command >> helpwin Search engine Printable documents Link to MathWorks 9

10 General Functions whos : List current variables and their size clear : Clear variables and functions from memory cd : Change current working directory dir : List files in directory pwd : Tells you the current directory you work in echo : Echo commands in M-files format : Set output format (long, short, etc.) diary (foo): Saves all the commands you type in in a file in the current directory called “ foo ” 10

11 Calculations at the Command Line »a = 2; »b = 5; »a^b ans = 32 »x = 5/2*pi; »y = sin(x) y = 1 »z = asin(y) z = »a = 2; »b = 5; »a^b ans = 32 »x = 5/2*pi; »y = sin(x) y = 1 »z = asin(y) z = Results assigned to “ans” if name not specified () parentheses for function inputs Semicolon suppresses screen output MATLAB as a calculator Assigning Variables A Note about Workspace: Numbers stored in double-precision floating point format » -5/( )^2 ans = » (3+4i)*(3-4i) ans = 25 » cos(pi/2) ans = e-017 » exp(acos(0.3)) ans = » -5/( )^2 ans = » (3+4i)*(3-4i) ans = 25 » cos(pi/2) ans = e-017 » exp(acos(0.3)) ans =

MATLAB for (linear) algebra 12

13 Matrices Entering and Generating Matrices Subscripts Scalar Expansion Concatenation Deleting Rows and Columns Array Extraction Matrix and Array Multiplication NOTE We don ’ t have time to carefully look at all these topics. Be aware that these facilities exist in MATLAB and that you can access them when needed by first invoking help on that command 13

14 »a=[1 2;3 4] a = »b=[-2.8, sqrt(-7), (3+5+6)*3/4] b = i »b(2,5) = 23 b = i »a=[1 2;3 4] a = »b=[-2.8, sqrt(-7), (3+5+6)*3/4] b = i »b(2,5) = 23 b = i Any MATLAB expression can be entered as a matrix element (internally, it is regarded as such) In MATLAB, the arrays are always rectangular Entering Numeric Arrays NOTE: 1) Row separator semicolon (;) 2) Column separator space OR comma (,) Use square brackets [ ] 14

15 The Matrix in MATLAB Rows (m) Columns (n) A = A (2,4) A (17) Rectangular Matrix: Scalar:1-by-1 array Vector:m-by-1 array 1-by-n array Matrix:m-by-n array 15

16 »w=[1 2;3 4] + 5 w = »x = 1:5 x = »y = 2:-0.5:0 y = »z = rand(2,4) z = »w=[1 2;3 4] + 5 w = »x = 1:5 x = »y = 2:-0.5:0 y = »z = rand(2,4) z = Scalar expansion Creating sequences: colon operator (:) Utility functions for creating matrices. Entering Numeric Arrays 16

17 Numerical Array Concatenation (Tiling) »a=[1 2;3 4] a = »cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a] cat_a = »a=[1 2;3 4] a = »cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a] cat_a = Use [ ] to combine existing arrays as matrix “elements” Row separator: semicolon (;) Column separator: space / comma (,) Use square brackets [ ] Note: The resulting matrix must be rectangular 4*a 17

18 Array Subscripting / Indexing A = A(3,1) A(3) A(1:5,5) A(:,5) A(21:25) A(4:5,2:3) A([9 14;10 15]) A(1:end,end) A(:,end) A(21:end)’ 18

19 Deleting Rows and Columns »A=[1 5 9; ; i+1] A = i »A(:,2)=[] A = i »A(2,2)=[] ??? Indexed empty matrix assignment is not allowed. »A=[1 5 9; ; i+1] A = i »A(:,2)=[] A = i »A(2,2)=[] ??? Indexed empty matrix assignment is not allowed. “:” is a VERY important construct in MATLAB 19

20 Matrix Multiplication »a = [ ; ]; »b = ones(4,3); »c = a*b c = »a = [ ; ]; »b = ones(4,3); »c = a*b c = [2x4] [4x3] »a = [ ; ]; »b = [1:4; 1:4]; »c = a.*b c = »a = [ ; ]; »b = [1:4; 1:4]; »c = a.*b c = c(2,4) = a(2,4)*b(2,4) Array Multiplication (component-wise operation) Array Multiplication 20

Matrix Manipulation Functions zeros : Create an array of all zeros ones : Create an array of all ones eye : Identity Matrix rand : Uniformly distributed random numbers diag : Diagonal matrices and diagonal of a matrix size : Return array dimensions fliplr : Flip matrices left-right (around a vertical axis) flipud : Flip matrices up-down (around horizontal axis) repmat : Replicate and tile a matrix reshape : Reshape array 21

Matrix Manipulation Functions transpose (’) : Transpose matrix rot90 : rotate matrix 90 tril : Lower triangular part of a matrix triu : Upper triangular part of a matrix cross : Vector cross product dot : Vector dot product det : Matrix determinant inv : Matrix inverse eig : Evaluate eigenvalues and eigenvectors rank : Rank of matrix 22

Elementary Math 23

24 Elementary Math Logical Operators Math Functions 24

25 Logical Operations » Mass = [-2 10 NaN Inf 31]; » each_pos = Mass>=0 each_pos = » all_pos = all(Mass>=0) all_pos = 0 » all_pos = any(Mass>=0) all_pos = 1 » pos_fin = (Mass>=0)&(isfinite(Mass)) pos_fin = » Mass = [-2 10 NaN Inf 31]; » each_pos = Mass>=0 each_pos = » all_pos = all(Mass>=0) all_pos = 0 » all_pos = any(Mass>=0) all_pos = 1 » pos_fin = (Mass>=0)&(isfinite(Mass)) pos_fin = = = equal to > greater than < less than >= Greater or equal <= less or equal ~ not & and | or isfinite(), etc.... all(), any() find Note: 1 = TRUE 0 = FALSE 25

Elementary Math Function abs, sign : Absolute value and signum function sin, cos, asin, acos, etc.: Trigonometric functions exp, log, log10 : Exponential, natural and common (base 10) logarithm ceil, floor : Round to integer, toward +/-infinity fix : Round to integer, toward zero 26

27 Elementary Math Function round : Round to the nearest integer gcd : Greatest common divisor lcm : Least common multiple sqrt : Square root function real, imag : Real and Imaginary part of complex rem : Remainder after division 27

Elementary Math Function Operating on Arrays max, min : Maximum and minimum of arrays mean, median : Average and median of arrays std, var : Standard deviation and variance sort : Sort elements in ascending order sum, prod : Summation and product of elements trapz : Trapezoidal numerical integration cumsum, cumprod : Cumulative sum, product diff, gradient : Differences and numerical gradient 28

Programming and Application Development 29

30 Topics discussed … The concept of m-file in MATLAB Script versus function files The concept of workspace Variables in MATLAB Type of a variable Scope of a variable Flow control in MATLAB The Editor/Debugger 30

Function M-file function r = ourrank(X,tol) % rank of a matrix s = svd(X); if (nargin == 1) tol = max(size(X)) * s(1)* eps; end r = sum(s > tol); function r = ourrank(X,tol) % rank of a matrix s = svd(X); if (nargin == 1) tol = max(size(X)) * s(1)* eps; end r = sum(s > tol); function [mean,stdev] = ourstat(x) [m,n] = size(x); if m == 1 m = n; end mean = sum(x)/m; stdev = sqrt(sum(x.^2)/m – mean.^2); function [mean,stdev] = ourstat(x) [m,n] = size(x); if m == 1 m = n; end mean = sum(x)/m; stdev = sqrt(sum(x.^2)/m – mean.^2); For input arguments, use ( ) Multiple output arguments, use [ ] »r=ourrank(rand(5),.1); »[m std]=ourstat(1:9); 31

Basic Parts of a Function M-File function y = mean(x) % MEAN Average or mean value. % For vectors, MEAN(x) returns the mean value. % For matrices, MEAN(x) is a row vector % containing the mean value of each column. [m,n] = size(x); if m == 1 m = n; end y = sum(x)/m; Output Arguments Input Arguments Function Name Online Help Function Code 32

Script and Function Files Script Files Work as though you type commands at the MATLAB prompt Stored in a file w/ extension.m The execution of a script doesn’t spawn a new workspace (more later) Function Files Let you make your own MATLAB Functions All information must be passed to functions as parameters There are input parameters and output parameters Function “foo” is stored inside file “foo.m” Name function +.m extension 33

The concept of Workspace At any time in a MATLAB session, the code has a workspace associated with it The workspace is like a sandbox in which you find yourself at a certain point of executing MATLAB code The “Base Workspace”: the workspace in which you live when you execute commands from prompt Remarks: Each MATLAB function has its own workspace (its own sandbox) A function invoked from a calling function has its own and separate workspace (sandbox) different from the caller’s workspace A script does not create a new workspace (unlike a function), but rather uses the workspace from which it was invoked 34

Variable Types in MATLAB Local Variables In general, a variable in MATLAB has local scope, that is, it’s only available in its workspace The variable disappears when the workspace ceases to exist Recall that a script does not define a new workspace – be careful, otherwise you can step on variables defined at the level where the script is invoked Since a function defines its own workspace, a variable defined in a function is local to that function Variables defined outside the function should be passed to function as arguments. Furthermore, the arguments are passed by value Every variable defined in the subroutine, if to be used outside the body of the function, should be returned back to the calling workspace 35

Variable Types in MATLAB Global Variables These are variables that are available in multiple workspaces They have to be explicitly declared as being global Not going to expand on this, since using global variables is a bad programming practice A note on returning values from a function Since all variables are local and input arguments are passed by value, when returning from a function a variable that is modified inside that function will not appear as modified in the calling workspace unless the variable is either global, or declared a return variable for that function 36

if ((attendance >= 0.90) & (grade_average >= 60)) pass = 1; end; if ((attendance >= 0.90) & (grade_average >= 60)) pass = 1; end; eps = 1; while (1+eps) > 1 eps = eps/2; end eps eps = 1; while (1+eps) > 1 eps = eps/2; end eps if Statement while Loops Flow Control Statements 37

a = zeros(k,k) % Preallocate matrix for m = 1:k for n = 1:k a(m,n) = 1/(m+n -1); end a = zeros(k,k) % Preallocate matrix for m = 1:k for n = 1:k a(m,n) = 1/(m+n -1); end method = 'Bilinear';... (some code here)... switch lower(method) case {'linear','bilinear'} disp('Method is linear') case 'cubic' disp('Method is cubic') otherwise disp('Unknown method.') end Method is linear method = 'Bilinear';... (some code here)... switch lower(method) case {'linear','bilinear'} disp('Method is linear') case 'cubic' disp('Method is cubic') otherwise disp('Unknown method.') end Method is linear for Loop: switch Statement: Flow Control Statements 38

39 Editing and Debugging M-Files The Editor/Debugger Debugging M-Files Types of Errors (Syntax Error and Exceptions) Using keyboard and “ ; ” statement Setting Breakpoints Stepping Through  Continue, Go Until Cursor, Step, Step In, Step Out Examining Values  Selecting the Workspace  Viewing Datatips in the Editor/Debugger  Evaluating a Selection 39

Debugging Select Workspace Set Auto- Breakpoints Tips Breakpoint 40

41 Importing and Exporting Data Using the Import Wizard Using the save and load commands load fname load fname x y z load fname -ascii load fname -mat load fname load fname x y z load fname -ascii load fname -mat save fname save fname x y z save fname -ascii save fname -mat save fname save fname x y z save fname -ascii save fname -mat 41

Read formatted data, reusing the format string N times. Suppose the text file stars.dat contains data in the following form: Jack Nicholson 71 No Yes 1.77 Helen Hunt 45 No No 1.73 >> fid = fopen(‘stars.dat’); >> C = textscan(fid, ‘%s%s%d%s%s%f’); >> fclose(fid); C is a 1x6 cell array, each cell containing a column of the data. Import and export numeric data from ASCII delimited file using dlmread/dlmwrite » C = textscan(fid,’format’,N); Input/Output for Text File » M = dlmread(filename,delimiter,range) 42

43 Input from Text File fopen: Open a file for input/output fgetl: Read line from file fclose: Close one or more open files » fid= fopen( ' myFile.txt ', ‘ r ' ); » str1= fgetl(fid); » fclose (fid); » fid= fopen( ' myFile.txt ', ‘ r ' ); » str1= fgetl(fid); » fclose (fid); 43

Miscellaneous 44

The inline Function inline function » f = inline('3*sin(2*x.^2)','x') f = Inline function: f(x) = 3*sin(2*x.^2) » f(2) ans = » f = inline('3*sin(2*x.^2)','x') f = Inline function: f(x) = 3*sin(2*x.^2) » f(2) ans = Use char function to convert inline object to string Numerical Quadrature using quad » Q = quad('1./(x.^3-2*x-5)',0,2); » F = inline('1./(x.^3-2*x-5)'); » Q = quad(F,0,2); » Q = quad('myfun',0,2) » Q = quad('1./(x.^3-2*x-5)',0,2); » F = inline('1./(x.^3-2*x-5)'); » Q = quad(F,0,2); » Q = quad('myfun',0,2) function y = myfun(x) y = 1./(x.^3-2*x-5); Note : quad function uses adaptive Simpson quadrature 45

Symbolic Math symbolic variable symbolic function » syms t; » func1=sym('3*cos(10*t)'); » syms t; » func1=sym('3*cos(10*t)'); » syms t; » func1=sym('3*cos(10*t)'); » value=subs(func1,t,2.3) value = » diff(func1) ans = (-30)*sin(10*t) » syms t; » func1=sym('3*cos(10*t)'); » value=subs(func1,t,2.3) value = » diff(func1) ans = (-30)*sin(10*t) Substitution symbolic differentiation 46

Graphics Fundamentals 47

48 Graphics and Plotting in MATLAB Basic Plotting plot, title, xlabel, grid, legend, hold, axis Editing Plots Property Editor Mesh and Surface Plots meshgrid, mesh, surf, colorbar, patch, hidden Handle Graphics 48

2-D Plotting Syntax: Example: plot(x1, y1, 'clm', x2, y2, 'clm',...) x=[0:0.1:2*pi]; y=sin(x); z=cos(x); plot(x,y,x,z,'linewidth',2) title('Sample Plot','fontsize',14); xlabel('X values','fontsize',14); ylabel('Y values','fontsize',14); legend('Y data','Z data') grid on x=[0:0.1:2*pi]; y=sin(x); z=cos(x); plot(x,y,x,z,'linewidth',2) title('Sample Plot','fontsize',14); xlabel('X values','fontsize',14); ylabel('Y values','fontsize',14); legend('Y data','Z data') grid on colorline marker 49

Sample Plot TitleYlabelXlabelGridLegend 50

51 Displaying Multiple Plots Nomenclature: Figure window – the window in which MATLAB displays plots Plot – a region of a window in which a curve (or surface) is displayed Three typical ways to display multiple curves in MATLAB (other combinations are possible … ) One figure contains one plot that contains multiple curves Requires the use of the command “ hold ” (see MATLAB help) One figure contains multiple plots, each plot containing one curve Requires the use of the command “ subplot ” Multiple figures, each containing one or more plots, each containing one or more curves Requires the use of the command “ figure ” and possibly “ subplot ” 51

Subplots Syntax: » subplot(2,2,1); » … » subplot(2,2,2) »... » subplot(2,2,3) »... » subplot(2,2,4) »... » subplot(2,2,1); » … » subplot(2,2,2) »... » subplot(2,2,3) »... » subplot(2,2,4) »... subplot(rows,cols,index) 52

53 The figure Command Use if you want to have several figures open for plotting The command by itself creates a new figure window and returns its handle >> figure If you have 20 figures open and want to make figure 9 the default one (this is where the next plot command will display a curve) do >> figure(9) >> plot( … ) Use the command close(9) if you want to close figure 9 in case you don ’ t need it anymore 53

Data Types 54

55 Data Types Numeric Arrays Multidimensional Arrays Structures and Cell Arrays 55

56 Multidimensional Arrays » A = pascal(4); » A(:,:,2) = magic(4) A(:,:,1) = A(:,:,2) = » A(:,:,9) = diag(ones(1,4)); » A = pascal(4); » A(:,:,2) = magic(4) A(:,:,1) = A(:,:,2) = » A(:,:,9) = diag(ones(1,4)); Page N Page The first references array dimension 1, the row. The second references dimension 2, the column. The third references dimension 3, the page. 56

Structures Arrays with named data containers called fields. » patient.name='John Doe'; » patient.billing = ; » patient.test= [ ; ; ]; » patient.name='John Doe'; » patient.billing = ; » patient.test= [ ; ; ]; Also, Build structure arrays using the struct function. Array of structures » patient(2).name='Katty Thomson'; » Patient(2).billing = ; » Patient(2).test= [ ; ; ]; » patient(2).name='Katty Thomson'; » Patient(2).billing = ; » Patient(2).test= [ ; ; ]; 57

Cell Arrays Array for which the elements are cells and can hold other MATLAB arrays of different types. » A(1,1) = {[1 4 3; 0 5 8; 7 2 9]}; » A(1,2) = {'Anne Smith'}; » A(2,1) = {3+7i}; » A(2,2) = {-pi:pi/10:pi}; » A(1,1) = {[1 4 3; 0 5 8; 7 2 9]}; » A(1,2) = {'Anne Smith'}; » A(2,1) = {3+7i}; » A(2,2) = {-pi:pi/10:pi}; Using braces {} to point to elements of cell array Using celldisp function to display cell array 58

59 Conclusion Matlab is a language of technical computing Matlab is a high-level language Matlab supports GUI, API, and … Matlab toolboxes are tailored for different applications Matlab is … 59

Getting more help Contact You can find more help and FAQ about MathWorks products on this page. Google group comp.soft-sys.matlabcomp.soft-sys.matlab ‘matlab’ tag on Use Google to find more information 60

JSON syntax & JSON in MATLAB 61

62 What is JSON? JavaScript Object Notation JSON is syntax for storing and exchanging text information. Much like XML. JSON is smaller than XML, faster and easier to parse. JSON: JSON is a lightweight text-data interchange format JSON is language-independent (the “JavaScript” in its name is misleading) JSON is "self-describing" and easy to understand (that’s why it doesn’t even provide for comments!) 62

63 Data Types and Syntax JSON’s basic types are: Number: usually double precision floating-point String: double-quoted Boolean: true or false Array: ordered sequence of values, comma- separated, enclosed in square brackets ‘[‘ and ‘]’ Object: unordered collection of key:value pairs, comma-separated, enclosed in curly braces ‘{‘ and ‘}’ null: empty Structural characters: [ ] { } :, White spaces have no semantics around the structural characters. 63

64 JSON Example { "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": }, "phoneNumbers": [ { "type": "home", "number": " “, “extension": 307 }, { "type": "fax", "number": " " } ] } key : value pair array object string number key : value pair Keys Values Structural characters 64

65 Reading JSON data in MATLAB No native MATLAB support Several third-party packages available jsonlab (developed by Qiangian Fang): (also available from the class website) Simple API Compact code Example usage: suppose the previous JSON data is in the file ‘demo.json’ Note that the file extension does not matter (.json is the standard extension) 65

Using the loadjson function >> data = loadjson('demo.json') data = firstName: 'John' lastName: 'Smith' age: 25 address: [1x1 struct] phoneNumbers: {[1x1 struct] [1x1 struct]} >> data.address ans = streetAddress: '21 2nd Street' city: 'New York' state: 'NY' postalCode: >> data.phoneNumbers ans = [1x1 struct] [1x1 struct] >> data.phoneNumbers(1) ans = [1x1 struct] >> data.phoneNumbers{1} ans = type: 'home' number: ' ' extension:

Hands-on Exercises 67

Exercise 1 Define a matrix A of dimension 2 by 4 whose (i,j) entry is A(i,j)=i+j Extract two 2 by 2 matrices A1 and A2 out of the matrix A. A1 contains the first two columns of A, A2 contains the last two columns of A Compute the matrix B to be the sum of A1 and A2 Compute the eigenvalues and eigenvectors of B Solve the linear system Bx=b, where b has all the entries equal to 1 Compute the determinant of B Compute the inverse of B Compute the condition number of B NOTE: Use only MATLAB native functions for all operations 68

69 Exercise 2: A debug session Use the function demoBisect provided on the next slide to run a debug session Save the MATLAB function to a file called demoBisect.m in the current directory Call once the demoBisect.m from the MATLAB prompt to see how it works >>help demoBisect >>demoBisect(0, 5, 30) Place some breakpoints and run a debug session Step through the code, and check the values of variables Use the MATLAB prompt to echo variables Use dbstep, dbcont, dbquit commands 69

function xm = demoBisect(xleft,xright,n) % demoBisect Use bisection to find the root of x - x^(1/3) - 2 % % Synopsis: x = demoBisect(xleft,xright) % x = demoBisect(xleft,xright,n) % % Input: xleft,xright = left and right brackets of the root % n = (optional) number of iterations; default: n = 15 % % Output: x = estimate of the root if nargin<3, n=15; end % Default number of iterations a = xleft; b = xright; % Copy original bracket to local variables fa = a - a^(1/3) - 2; % Initial values of f(a) and f(b) fb = b - b^(1/3) - 2; fprintf(' k a xmid b f(xmid)\n’); for k=1:n xm = a + 0.5*(b-a); % Minimize roundoff in computing the midpoint fm = xm - xm^(1/3) - 2; % f(x) at midpoint fprintf('%3d %12.8f %12.8f %12.8f %12.3e\n’,k,a,xm,b,fm); if sign(fm)==sign(fa) % Root lies in interval [xm,b], replace a a = xm; fa = fm; else % Root lies in interval [a,xm], replace b b = xm; fb = fm; end 70