MATLAB Basics.

Slides:



Advertisements
Similar presentations
Multidimensional Array
Advertisements

Introduction to Matlab
MATLAB Basics CS 111 Introduction to Computing in Engineering and Science.
Introduction to MATLAB
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.
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.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
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.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
INTRODUCTION TO MATLAB LAB# 01
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Matlab Programming for Engineers Dr. Bashir NOURI Introduction to Matlab Matlab Basics Branching Statements Loops User Defined Functions Additional Data.
Getting Started with MATLAB 1. Fundamentals of MATLAB 2. Different Windows of MATLAB 1.
Introduction to Engineering MATLAB – 2 Introduction to MATLAB - 2 Agenda Defining Variables MATLAB Windows.
10/24/20151 Chapter 2 Review: MATLAB Environment Introduction to MATLAB 7 Engineering 161.
Introduction to Programming with RAPTOR
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
ME6104: CAD. Module 4. ME6104: CAD. Module 4. Systems Realization Laboratory Module 4 Matlab ME 6104 – Fundamentals of Computer-Aided Design.
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
Lecture 20: Choosing the Right Tool for the Job. What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
A simple classification problem Extract attributes Pattern Pattern recognition decision x C1 C2.
Introduction to Matlab Electromagnetic Theory LAB by Engr. Mian Shahzad Iqbal.
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.
Matlab for Engineers Matlab Environment Chapter 2.
MATLAB Lecture 1 염익준. Introduction MATLAB (MATrix LABoratory) a special purpose computer program optimized to perform engineering and scientific calculations.
Interduction to MATLAB (part 2) Manal Alotaibi Mathematics department College of science King saud university.
MATLAB Constants, Variables & Expression Nafees Ahmed Asstt. Professor, EE Deptt DIT, DehraDun.
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
Introduction to Matlab Engr. Mian Shahzad Iqbal LAB NO.2
ECE 1304 Introduction to Electrical and Computer Engineering
Topics Designing a Program Input, Processing, and Output
BASIC ELEMENTS OF A COMPUTER PROGRAM
Control Statements in Matlab
Statistical Computing in MATLAB
Other Kinds of Arrays Chapter 11
Other Kinds of Arrays Chapter 11
2) Platform independent 3) Predefined functions
INTRODUCTION TO BASIC MATLAB
MATLAB DENC 2533 ECADD LAB 9.
Introduction to Matlab
Matlab Workshop 9/22/2018.
StatLab Matlab Workshop
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Use of Mathematics using Technology (Maltlab)
StatLab Workshop: Intro to Matlab for Data Analysis and Statistical Modeling 11/29/2018.
Lecture 2 Introduction to MATLAB
Introduction to MATLAB
PHP.
Computational Methods
Introduction to Matlab
Loop Statements & Vectorizing Code
INTRODUCTION TO MATLAB
Topics Designing a Program Input, Processing, and Output
Experiment No. (1) - an introduction to MATLAB
Topics Designing a Program Input, Processing, and Output
Announcements P3 due today
Introduction to Matlab
CS 111 Introduction to Computing in Engineering and Science
Introduction to MATLAB
Arrays in Matlab UC Berkeley Fall 2004, E Copyright 2005, Andy Packard
Matlab Basics.
Loop Statements & Vectorizing Code
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
MatLab Program Used to Calculate Interactive
Presentation transcript:

MATLAB Basics

MATrix LABoratory www.mathworks.com Advantages of MATLAB Ease of use Platform independence Predefined functions Plotting Disadvantages of MATLAB Can be slow Commercial software

Matlab Windows Command line Interface ( Main Window) Editor Window Present Directory Directory Contents and Workspace variables Command line Command History Command line Interface ( Main Window) Editor Window

MATLAB BASICS Variables and Arrays Array: A collection of data values organized into rows and columns, and known by a single name. Row 1 Row 2 Row 3 arr(3,2) Row 4 Col 1 Col 2 Col 3 Col 4 Col 5

MATLAB BASICS Arrays The fundamental unit of data in MATLAB Scalars are also treated as arrays by MATLAB (1 row and 1 column). Row and column indices of an array start from 1. Arrays can be classified as vectors and matrices.

MATLAB BASICS Vector: Array with one dimension Matrix: Array with more than one dimension Size of an array is specified by the number of rows and the number of columns, with the number of rows mentioned first (For example: n x m array). Total number of elements in an array is the product of the number of rows and the number of columns.

MATLAB BASICS 1 2 3 4 5 6 a= 3x2 matrix  6 elements b=[1 2 3 4] 1 2 3 4 5 6 a= 3x2 matrix  6 elements b=[1 2 3 4] 1x4 array  4 elements, row vector 1 3 5 c= 3x1 array  3 elements, column vector a(2,1)=3 b(3)=3 c(2)=3 Row # Column #

MATLAB BASICS Multidimensional Arrays A two dimensional array with m rows and n columns will occupy mxn successive locations in the computer’s memory. MATLAB always allocates array elements in column major order. a= [1 2 3; 4 5 6; 7 8 9; 10 11 12]; a(5) = a(1,2) = 2 A 2x3x2 array of three dimensions c(:, :, 1) = [1 2 3; 4 5 6 ]; c(:, :, 2) = [7 8 9; 10 11 12]; 1 4 1 2 3 7 4 5 6 10 7 8 9 2 10 11 12 5 8 11

MATLAB BASICS Variables Variable names must begin with a letter, followed by any combination of letters, numbers and the underscore (_) character. The MATLAB language is Case Sensitive. NAME, name and Name are all different variables. Give meaningful (descriptive and easy-to-remember) names for the variables. Never define a variable with the same name as a MATLAB function or command.

MATLAB BASICS Common types of MATLAB variables double: 64-bit double-precision floating-point numbers They can hold real, imaginary or complex numbers in the range from ±10-308 to ±10308 with 15 or 16 decimal digits. >> var = 1 + i ; char: 16-bit values, each representing a single character The char arrays are used to hold character strings. >> comment = ‘This is a character string’ ; The type of data assigned to a variable determines the type of variable that is created.

MATLAB BASICS Initializing Variables in Assignment Statements An assignment statement has the general form var = expression Examples: >> var = 40 * i; >> a2 = [0 1+8]; >> var2 = var / 5; >> b2 = [a2(2) 7 a]; >> array = [1 2 3 4]; >> c2(2,3) = 5; >> x = 1; y = 2; >> d2 = [1 2]; >> a = [3.4]; >> d2(4) = 4; >> b = [1.0 2.0 3.0 4.0]; >> c = [1.0; 2.0; 3.0]; >> d = [1, 2, 3; 4, 5, 6]; ‘;’ semicolon suppresses the >> e = [1, 2, 3 automatic echoing of values but 4, 5, 6]; it slows down the execution.

MATLAB BASICS Initializing Variables in Assignment Statements Arrays are constructed using brackets and semicolons. All of the elements of an array are listed in row order. The values in each row are listed from left to right and they are separated by blank spaces or commas. The rows are separated by semicolons or new lines. The number of elements in every row of an array must be the same.

MATLAB BASICS Initializing with Shortcut Expressions first: increment: last Colon operator: a shortcut notation used to initialize arrays with thousands of elements >> x = 1 : 2 : 10; >> angles = (0.01 : 0.01 : 1) * pi; Transpose operator: (′) swaps the rows and columns of an array >> g = [1:4]; >> h = [ g′ g′ ]; 1 1 2 2 3 4 4 h=

MATLAB BASICS Initializing with Built-in Functions zeros(n) >> a = zeros(2); zeros(n,m) >> b = zeros(2, 3); zeros(size(arr)) >> c = [1, 2; 3, 4]; ones(n) >> d = zeros(size(c)); ones(n,m) ones(size(arr)) eye(n) eye(n,m) length(arr) size(arr)

MATLAB BASICS Initializing with Keyboard Input The input function displays a prompt string in the Command Window and then waits for the user to respond. my_val = input( ‘Enter an input value: ’ ); in1 = input( ‘Enter data: ’ ); in2 = input( ‘Enter data: ’ ,`s`);

MATLAB BASICS Subarrays The end function: When used in an array subscript, it returns the highest value taken on by that subscript. arr3 = [1 2 3 4 5 6 7 8]; arr3(5:end) is the array [5 6 7 8] arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12]; arr4(2:end, 2:end)

MATLAB BASICS Subarrays Assigning a Scalar to a Subarray: A scalar value on the right-hand side of an assignment statement is copied into every element specified on the left-hand side. >> arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12]; >> arr4(1:2, 1:2) = 1 arr4 = 1 1 3 4 1 1 7 8 9 10 11 12

MATLAB BASICS Special Values MATLAB includes a number of predefined special values. These values can be used at any time without initializing them. These predefined values are stored in ordinary variables. They can be overwritten or modified by a user. If a new value is assigned to one of these variables, then that new value will replace the default one in all later calculations. >> circ1 = 2 * pi * 10; >> pi = 3; >> circ2 = 2 * pi * 10; Never change the values of predefined variables.

MATLAB BASICS Special Values pi:  value up to 15 significant digits i, j: sqrt(-1) Inf: infinity (such as division by 0) NaN: Not-a-Number (division of zero by zero) clock: current date and time in the form of a 6-element row vector containing the year, month, day, hour, minute, and second date: current date as a string such as 16-Feb-2004 eps: epsilon is the smallest difference between two numbers ans: stores the result of an expression

MATLAB BASICS Changing the data format >> value = 12.345678901234567; format short  12.3457 format long  12.34567890123457 format short e  1.2346e+001 format long e  1.234567890123457e+001 format short g  12.346 format long g  12.3456789012346 format rat  1000/81

MATLAB BASICS The disp( array ) function >> disp( 'Hello' ) 5 >> disp( [ 'Bilkent ' 'University' ] ) Bilkent University >> name = 'Alper'; >> disp( [ 'Hello ' name ] ) Hello Alper

MATLAB BASICS The num2str() and int2str() functions >> d = [ num2str(16) '-Feb-' num2str(2004) ]; >> disp(d) 16-Feb-2004 >> x = 23.11; >> disp( [ 'answer = ' num2str(x) ] ) answer = 23.11 >> disp( [ 'answer = ' int2str(x) ] ) answer = 23

MATLAB BASICS The fprintf( format, data ) function %d integer %f floating point format %e exponential format %g either floating point or exponential format, whichever is shorter \n new line character \t tab character

MATLAB BASICS >> fprintf( 'Result is %d', 3 ) Result is 3 >> fprintf( 'Area of a circle with radius %d is %f', 3, pi*3^2 ) Area of a circle with radius 3 is 28.274334 >> x = 5; >> fprintf( 'x = %3d', x ) x = 5 >> x = pi; >> fprintf( 'x = %0.2f', x ) x = 3.14 >> fprintf( 'x = %6.2f', x ) x = 3.14 >> fprintf( 'x = %d\ny = %d\n', 3, 13 ) x = 3 y = 13

MATLAB BASICS Data files save filename var1 var2 … load filename >> save myfile.mat x y  binary >> save myfile.dat x –ascii  ascii load filename >> load myfile.mat  binary >> load myfile.dat –ascii  ascii

MATLAB BASICS variable_name = expression; addition a + b  a + b subtraction a - b  a - b multiplication a x b  a * b division a / b  a / b exponent ab  a ^ b

MATLAB BASICS Hierarchy of operations x = 3 * 2 + 6 / 2 Processing order of operations is important parentheses (starting from the innermost) exponentials (from left to right) multiplications and divisions (from left to right) additions and subtractions (from left to right) >> x = 3 * 2 + 6 / 2 x = 9

MATLAB BASICS Built-in MATLAB Functions result = function_name( input ); abs, sign log, log10, log2 exp sqrt sin, cos, tan asin, acos, atan max, min round, floor, ceil, fix mod, rem help elfun  help for elementary math functions

Flow Control Constructs Logic Control: IF / ELSEIF / ELSE SWITCH / CASE / OTHERWISE Iterative Loops: FOR WHILE These MATLAB commands provide structural constructs for controlling the flow of logic within a program. They will be discussed further in the slides which follow. 29

The if, elseif and else statements if I == J A(I,J) = 2; elseif abs(I-J) == 1 A(I,J) = -1; else A(I,J) = 0; end Works on Conditional statements Short-circuited in MATLAB - once a condition is true, the sequence terminates. A conditional (boolean) statement is an expression which tests the validity of a specified condition (e.g., I==J). The following result is returned: TRUE - 1 FALSE - 0 MATLAB starts at the beginning of the IF / ELSEIF / ELSE sequence and proceeds from on condition to the next. When it find a true statement, it executes the appropriate section of the code and then terminates the sequence. The last section of code is closed using the keyword “end.” 30

Switch, Case, and Otherwise switch input_num case -1 input_str = 'minus one'; case 0 input_str = 'zero'; case 1 input_str = 'plus one'; case {-10,10} input_str = '+/- ten'; otherwise input_str = 'other value'; end More efficient than elseif statements Only the first matching case is executed The switch statement is a convenient way to execute conditional code when you have many possible cases to choose from. This function can be used in place of a series of elseif statements. The code above shows a simple example of the switch statement. It checks the variable input_num for certain values. If input_num is -1, 0, or 1, the case statements display the value on screen as text. If input_num is none of these values, execution drops to the otherwise statement and the code displays the test ‘other value’. Only the first matching case is executed. This function could also be created using IF / ELSEIF / ELSE commands: if input_num == -1 disp(‘negative one’); elseif input_num == 0 disp(‘zero’); elseif input_num == 1 disp(‘positive one’); else disp(‘other value’); end The use of the switch case allows the function to run more efficiently. NOTE FOR C PROGRAMMERS: Unlike in C, MATLAB’s switch does not “fall through”. That is, if the first case statement is TRUE, other case statements do not execute. Therefore, break statements are not used. 31

The for loop Similar to other programming languages N=10; for I = 1:N Repeats loop a set number of times (based on index) Can be nested N=10; for I = 1:N for J = 1:N A(I,J) = 1/(I+J-1); end The FOR loop repeats a section of code a set number of times. FOR loops can be nested (one inside the other) and each loop is closed with “end”. 32

The while loop Similar to other programming languages Repeats loop until logical condition returns FALSE. Can be nested. I=1; N=10; while I<=N J=1; while J<=N A(I,J)=1/(I+J-1); J=J+1; end I=I+1; The WHILE loop will continue to repeat a section of code until its conditional statement is false (returns 0). WHILE loops can be nested (one inside the other) and each loop is closed with “end”. WARNING: Watch out for infinite loops. 33

MATLAB BASICS Types of errors in MATLAB programs Syntax errors Check spelling and punctuation Run-time errors Check input data Can remove “;” or add “disp” statements Logical errors Use shorter statements Check typos Check units Ask assistants, instructor, …

Matlab Graphs x = 0:pi/100:2*pi; y = sin(x); plot(x,y) xlabel('x = 0:2\pi') ylabel('Sine of x') title('Plot of the Sine Function')

Multiple Graphs t = 0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); plot(t,y1,t,y2) grid on

MATLAB BASICS Summary help command  Online help lookfor keyword  Lists related commands which  Version and location info clear  Clears the workspace clc  Clears the command window diary filename  Sends output to file diary on/off  Turns diary on/off who, whos  Lists content of the workspace more on/off  Enables/disables paged output Ctrl+c  Aborts operation …  Continuation %  Comments