Yuval Hart, Weizmann 2010 © 1 Introduction to Matlab & Data Analysis Tutorial 2 and 3: Variables and Matrix Manipulation.

Slides:



Advertisements
Similar presentations
Introduction to M ATLAB Programming Ian Brooks Institute for Climate & Atmospheric Science School of Earth & Environment
Advertisements

Introduction to Matlab
Introduction to Matlab Workshop Matthew Johnson, Economics October 17, /13/20151.
Lecture 4.
MATLAB – What is it? Computing environment / programming language Tool for manipulating matrices Many applications, you just need to get some numbers in.
CIS 101: Computer Programming and Problem Solving Lecture 7 Usman Roshan Department of Computer Science NJIT.
CIS 101: Computer Programming and Problem Solving Lecture 2 Usman Roshan Department of Computer Science NJIT.
Eilon Sharon, Weizmann 2008 © 1 Introduction to Matlab & Data Analysis Tutorial 2: Variables and Matrix Manipulation.
Concatenation MATLAB lets you construct a new vector by concatenating other vectors: – A = [B C D... X Y Z] where the individual items in the brackets.
Matrix Mathematics in MATLAB and Excel
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.
Matlab intro The Environment
Introduction to MATLAB ENGR 1187 MATLAB 1. Programming In The Real World Programming is a powerful tool for solving problems in every day industry settings.
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.
1 MATLAB 基礎. 2 MATLAB  Workspace: environment (address space) where all variables reside  After carrying out a calculation, MATLAB assigns the result.
1 Introduction to MATLAB MATLAB is all of the following: 1.Computational environment 2.Plotting software 3.Programming language Typical applications: 1.Calculations.
Matlab tutorial course Lesson 2: Arrays and data types
MATLAB INTRO CONTROL LAB1  The Environment  The command prompt Getting Help : e.g help sin, lookfor cos Variables Vectors, Matrices, and Linear Algebra.
Martin Ellison University of Warwick and CEPR Bank of England, December 2005 Introduction to MATLAB.
Engineering Analysis ENG 3420 Fall 2009 Dan C. Marinescu Office: HEC 439 B Office hours: Tu-Th 11:00-12:00.
Nonparametric Econometrics1 Intro to Matlab for Data Analysis and Statistical Modeling.
Introduction to MATLAB Session 1 Prepared By: Dina El Kholy Ahmed Dalal Statistics Course – Biomedical Department -year 3.
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
MATLAB Tutorials Session I Introduction to MATLAB Rajeev Madazhy Dept of Mechanical Engineering LSU.
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.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
CSE123 Lecture 5 Arrays and Array Operations. Definitions Scalars: Variables that represent single numbers. Note that complex numbers are also scalars,
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.
ECE 1304 Introduction to Electrical and Computer Engineering Section 1.1 Introduction to MATLAB.
Introduction to MATLAB ENGR 1181 MATLAB 1. Programming In The Real World Programming is a powerful tool for solving problems in every day industry settings.
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.
What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation tools. Others include Maple Mathematica MathCad.
Matlab Programming for Engineers Dr. Bashir NOURI Introduction to Matlab Matlab Basics Branching Statements Loops User Defined Functions Additional Data.
Lecture 2 - Matlab Introduction CVEN 302 June 5, 2002.
Introduction to MATLAB Session 1 Simopekka Vänskä, THL 2010.
Octave. Getting Started Arithmetic is as usual: – What would (a-V)(V-1)V be for a=0.1 and V=-56? – Multiplication is *, division is /
A string is an array of characters Strings have many uses in MATLAB Display text output Specify formatting for plots Input arguments for some functions.
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
Chapter 2 Creating Arrays Legend: MATLAB command or syntax : Blue MATLAB command OUTPUT : LIGHT BLUE.
Part 1 Chapter 2 MATLAB Fundamentals PowerPoints organized by Dr. Michael R. Gustafson II, Duke University and Prof. Steve Chapra, Tufts University All.
Lecture 20: Choosing the Right Tool for the Job. What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation.
(The Transpose Operator) 1 >> C=[ ; ; ] C = >> D=C' D =
Introduction to Matlab  Matlab is a software package for technical computation.  Matlab allows you to solve many numerical problems including - arrays.
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
Introduction to Engineering MATLAB – 4 Arrays Agenda Creating arrays of numbers  Vectors: 1-D Arrays  Arrays: 2-D Arrays Array Addressing Strings & String.
September 15, 2005 Lecture 5 - By Paul Lin 1 CPET 190 Lecture 5 Problem Solving with MATLAB
1 Lecture 3 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
Matlab for Engineers Matlab Environment Chapter 2.
CMPS 1371 Introduction to Computing for Engineers VECTORS.
CSE 455 : Computer Vision MATLAB 101 Getting Started with MATLAB.
1 Faculty Name Prof. A. A. Saati. 2 MATLAB Fundamentals 3 1.Reading home works ( Applied Numerical Methods )  CHAPTER 2: MATLAB Fundamentals (p.24)
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
Manipulating MATLAB Vector, Matrices 1. Variables and Arrays What are variables? You name the variables (as the programmer) and assign them numerical.
CS100A, Fall 1998, Lecture 201 CS100A, Fall 1998 Lecture 20, Tuesday Nov 10 More Matlab Concepts: plotting (cont.) 2-D arrays Control structures: while,
Lecture 12: M/O/F/ for Engineering Applications B Burlingame 27 April 2016.
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.
Introduction to MATLAB for Engineers, Third Edition
Chapter 3 Arrays and Vectors
MATLAB DENC 2533 ECADD LAB 9.
Matlab Workshop 9/22/2018.
StatLab Matlab Workshop
MATH 493 Introduction to MATLAB
StatLab Workshop: Intro to Matlab for Data Analysis and Statistical Modeling 11/29/2018.
Matlab tutorial course
Lecture 2 Introduction to MATLAB
Vectors and Matrices I.
Matlab Basics Tutorial
Presentation transcript:

Yuval Hart, Weizmann 2010 © 1 Introduction to Matlab & Data Analysis Tutorial 2 and 3: Variables and Matrix Manipulation

2 Goals Introduce the Notion of Variables & Data Types. Master Arrays manipulation Learn Arrays Mathematical Operations Learn Basic String Manipulations Learn to Use Array Editor Solving Linear System of Equations

Yuval Hart, Weizmann 2010 © 3 Variables

4 A MATLAB variable is an identified piece of data (= the assigned value) The value is kept in the memory The identifier provides a reference to the value such that your program can: Read it Use it for computation / change its value and save it back to memory

5 Variable Assignment max_grade = 100; Assignment operator Value Variable identifier (name): Letters Digits Underscore 1.Can’t start with a number 2.Case sensitive!!! 3.Can’t be a keyword clear max_grade; clear; clear all;

6 Variable - Hands On Exercise 1: Consider the following: x = 50; disp = 100; disp(x); builtin(‘disp’, x); clear disp; disp(x); What happened? The disp variable overrides the disp built-in function Don’t override built-in functions!!!

7 Variable - Hands On (II) Exercise 2: Define a variable “grade” and assign the value 80 to it. “Personal Factor” - Now add to the grade its square root (there are several options to solve this…) Define a “classFactor” and assign 10 to it. Define a “finalGrade” variable and assign the value of the factored grade plus the class factor to it. What is the final grade? Lets look at the workspace window. Try to change grade value to 100.

8 Workspace functions which(‘linspace’); locates a function or identifies as variable clear x; save(‘file_name’, ‘var1’, ‘var2’, …) saves the workspace to a “.mat” file load(‘file_name’); loads variables from a “.mat” file into the workspace Example: Create some a,b,c variables save(‘tutorial2.mat’, ‘a’, ‘b’,’c’); clear; Load(‘tutorial2.mat’)

Yuval Hart, Weizmann 2010 © 9 Data Types

10 Data Types (Variable types) Everything in Matlab is an array! Next lectures… A scalar is also an array of size 1x1

11 Data Types (Variable Types) Default Integer

12 Data types - Numeric Integer: a = int16(100); Be careful of memory overflow b = int8(5000); Real(/Complex): x = double(235.5); x = single(235.5); x = 235;

13 Numeric Data Functions A summery of numeric functions: Help -> contents -> MATLAB -> Functions -> Mathematics -> Array and Matrices (and also the rest of the items…) Notice: isinf, isnan, floor, ceil Infinite Is Not A Number

Yuval Hart, Weizmann 2010 © 14 Arrays Manipulation

15 Arrays and Matrices A Matlab variable is an array. A one dimensional array is named vector A two dimensional array is named matrix Creating arrays Which are equal? a = [ ]; b = [1, 2, 3, 4]; c = [1; 2; 3; 4]; d =1:1:4; e = (1:4)’; Space / comma – New element in same line New line / Semicolon – new line Colon operator – from:step:to. Default step is one. ‘ operator- transpose (near the enter key)

16 linspace and logspace linspace(0,100,51); Why? Consider 0:0.33:1 or 0:0.08:1 logspace(1,10,11); Same, but logarithmically spaced between 10^1 and 10^10 Min valueMax valueNumber of points

17 Drawing the Sine and Cosine Functions Use the commands we learned to define x as: Compute y and z – the sine and cosine function of x respectively. Draw a plot of the sine and cosine function of [-π, π] using the following code: hold off; plot(x,y,'b-'); hold on; plot(x,z,'r-'); legend('Sine', 'Cosine'); x = linspace(-pi,pi, 21); % another way: x = (-1:0.1:1) * pi; y = sin(x); z = cos(x); Reminder:linspace

18 Multidimensional Array Indexing A = [1, 2, 3; 4, 5, 6; 7, 8, 9] Multi dimensional arrays: B(:, :, 1) = A; B(:, :, 2) = A; B(:, :, 3) = A; Getting the matrix size: size(A) See also: length(A) numel(A) Subscripts to single index: sub2ind(size(A), 2,3) A(2,3) A(8) A = First dimension (Row) Second dimension (Column) B = Third dimension (Page) ans = 3 3 ans =

19 Arrays Manipulation a = [1, 2; 3, 4] a = a’ % or a.’ ans= a(2) a(:) ans= ans = a(1,end:-1:1) ans = 2 1 b = fliplr(a) ans = c = flipud(a) ans = The last coordinate in the dimension Array flattening

20 Arrays Manipulation– More… d = 1:2:9 d = e = 2:2:10 e = f = [d; e] f = g = [d(1:3), e] g = reshape(a,1,4) ans = repmat(e,2,2) ans = Horizontal Array Concatenation See also: diag() Vertical Array Concatenation

21 Assignment into Array >> A = [1, 2, 3; 4, 5, 6; 7, 8, 9] A = >> A(3,4) ??? Index exceeds matrix dimensions. >> A(4,4) = 10 A = ? Notice the difference!

22 Assignment into Array >> A = [1, 2, 3; 4, 5, 6; 7, 8, 9] A = >> A(:) = 21:30 ??? In an assignment A(:) = B, the number of elements in A and B must be the same. >> B = [21, 22, 23; 24, 25, 26] B = >> A(1:2,1:3) = B A = Notice the difference! >> A(1:2,1:3) = 10 A = Subscripted assignment dimension must match! Scalar expansion

23 Example - Image Manipulation Images are represented by matrices Lets use this to visualize matrix manipulation “Andy Warhol” style

24 Standard Arrays zeros(10,10) ones(10,10) rand(10,10) randn(10,10) eye(10,10) What is it good for? Allocate memory in advance! Create a sample. Identity matrix

25 Find & logical Arrays >> A = magic(3) A = >> is_larger_than5 = A > 5 is_larger_than5 = >> class(is_larger_than5) ans = Logical >> A(is_larger_than5) ans = >> index_larger_than5 = find(A>5) index_larger_than5 = >> A(index_larger_than5) = 10 % A(find(A>5))= 10 A = >> [r c] = find(A>5) r = c = >> A(r,c) = 20 % wrong! A = Logical operator Logical array Array can be indexed with logical array! Array of indices Assignment using indices array Matlab functions output depends on the # of output parameters! find can return subscripts What is wrong? A([ ], [ ]) = 20

26 Short Example Consider the martix: A = magic(6); Try to run A(1:3,1:3) = ones(7,7); What did you get? Replace all element larger than 20 with the value 100 Now, make A be only its last three columns Then compute the mean of the fourth row. A = magic(6) A(:,:) = ones(7,7) ??? Subscripted assignment dimension mismatch. A( find(A > 20) ) = 100; A = A(:,4:6); % or A(:,1:3) = []; mean(A(4,:))

Yuval Hart, Weizmann 2010 © 27 Arrays mathematical operations

28 Array arithmetic Element by element: A+B A-B -A A.*B A./B A.\B.^ Matrices dimensions must match + * /\ by scalar are element-wise Search help for : “Arithmetic Operators“ C = A*B : A #columns == B #rows A^p Try to run the following: x = 1:3; y = x'; x.* y' x*y y*x

29 “Grades” Exercise Revisited We want to compute the final grade as follows: Multiply each grade by the class participation score Then add 10 points to all grades? Grade Participation in class Consider the following: >> grades = [ ]; >> participation_in_class= [1.10,1.05, 1.07, 0.99, 1.10]; >> final_grades = (grades.* participation_in_class) + 10 final_grades = Answer:

Yuval Hart, Weizmann 2010 © 30 String Manipulations

31 Strings as Char Arrays s=‘I am a string’s = I am a string s(1:4)ans = I am [s([1:9,6,10]) '!']I am a star! s(end:-1:1)ans = gnirts a ma I Strings are represented as Char array Assigning a string: a=‘I am a string’ >> a = 'It is easy '; >> b = 'to concatenate strings!'; >> [a, b] ans = It is easy to concatenate strings! Char arrays can be concatenated like numerical arrays Lets try it:

32 Working with Strings – Generating Output >> c = num2str( ) c = >> class(c) ans = char >> d = str2num(c) d = >> class(d) ans = double >> ['pie value is: ' num2str( )] ans = pie value is: Tip num2str str2num Are very useful for output string generation

33 Working with strings – char matrices >> str_mat = ['one ' 'two ' 'three'] str_mat = one two three >> class(str_mat) ans = char >> size(str_mat) ans = 3 5 >> str_mat = … char('one','two','three') str_mat = one two Three Rows length must be equal! (a square matrix) Concatenate vertically!

34 Working with Strings – String Comparison >> strcmp('abcd','abc') ans = 0 >> strncmp('abcd','abc',3) ans = 1 Compare the strings Compare the first “n” characters of the two strings Check also: strfind

Yuval Hart, Weizmann 2010 © 35 Array Editor

36 Array Editor and Array Display Display: Omitting the “;” disp(‘hello world’); [‘Today we added’ num2str() ] Example: three = 2; [ ‘ One plus one is: ' num2str(three)] Array Editor: From: work space, “open selection” Displays variables Edit variables value Copy-paste from Excel (grades example)

Yuval Hart, Weizmann 2010 © 37 Solving Linear System of Equations

38 Say we want to solve the following system: A = [ ; ; ]; b = [3; 1; 4]; x = A\b; Solution: x = More: search help “solving linear equations” Epilogue - Solving Linear Systems of Equations Ax=b

39 Epilogue - Solving Linear Systems of Equations Solve the following problem: 1x+2y+3z = 366 4x+5y+6z= 804 7x+8y = 351 Answer: A = [ ]; b = [366; 804; 351]; x = A\b Result: x =

40 Summary Introduce the Notion of Variables & Data Types. Master Arrays manipulation Learn Arrays Mathematical Operations Learn Simple String Manipulations Learn to Use Array Editor Solving Linear System of Equations