SlideShare a Scribd company logo
CIV1900: Engineering Skills
Variables in MATLAB
Variables allow you to store (intermediate) results
• a variable is a named location in computer memory
• for storing/retrieving one or more values
• created in MATLAB by assignment
radius = 3
• accessed by mentioning the name (or in Workspace)
>>radius
radius =
3
• can be used anywhere a number (literal) can be used
area = pi*radius^2
CIV1900 Engineering Skills: programming in MATLAB 2
Variables in MATLAB
• variables are listed in alphabetical order in the Workspace
• with information about their name, size, type and min/max
• not all information is shown automatically
• use View > Choose Columns when focus is in the Workspace
• MATLAB automatically creates a variable called ans if
needed:
>> 1024^3/8
ans=
134217728
• If you don't want to print out the result add a semi-colon
>> diameter = 2*radius;
3Engineering Skills: programming in MATLABCIV1900
Assignment might look like algebra, but it isn't
• x = x + 1 doesn't sound right
• how can x be equal to x + 1
• why isn't it a logical inconsistency?
• because assignment isn't equality at all
• assignment is a two step process:
• calculate the value on the right hand side (r-value)
• store the result in the variable on the left hand side (l-value)
• So x = x + 1 means:
• evaluate x + 1 first by getting the value out of variable x
• store the result back into variable x
4Engineering Skills: programming in MATLABCIV1900
MATLAB arrays are collections of (like) values
• arrays store multiple elements of one type
• each element can be accessed by position in the array
• called indexing or subscripting the array
• uses the array name and then the index in
parentheses
• most other programming languages index from 0
5Engineering Skills: programming in MATLABCIV1900
1-dimensional arrays are called vectors
• created with square brackets and (optional) commas
pos = [1, 0, -1]
primes = [1 2 3 5 7 11 13]
• accessed with indices e.g. the 6th prime number is?
primes(6)
ans =
11
• notice how vectors appear in the Workspace (e.g. size 1x7)
6Engineering Skills: programming in MATLABCIV1900
Vectors can be created using n:s:m notation
• vectors ranging from n to m with step s can be written n:s:m
e.g. from 1 to 20 stepping by 3:
x = 1:3:20
x =
1 4 7 10 13 16 19
• if the step size is missing, the default is 1:
x = 1:7
x =
1 2 3 4 5 6 7
• the vector goes up to and including the last value
• think about what might happen with negative values!
7Engineering Skills: programming in MATLABCIV1900
MATLAB has functions to create vectors with fixed sizes
• linspace takes a n and m, and a number of elements:
• e.g. create a vector from 0 to 3 containing 5 values
linspace(0, 3, 5)
ans =
0 0.7500 1.5000 2.2500 3.0000
• zeros and ones create vectors of only zeros and ones
zeros(1, 5)
ans =
0 0 0 0 0
ones(1, 5)
ans =
1 1 1 1 1
8Engineering Skills: programming in MATLABCIV1900
Indexing is used to make vectors longer or shorter
• assigning to an index beyond the length grows the vector
data = [1 2 3];
data(6) = -1
data =
1 2 3 0 0 -1
• zeros are used to fill in the gaps
• assigning an empty vector to an index removes elements
data(2) = []
data =
1 3 0 0 -1
9Engineering Skills: programming in MATLABCIV1900
Boolean vectors can be used to select elements
• booleans are true/false (that is, yes/no values) of type logical
primes = [1 2 3 5 7 11 13];
mask = [true false true false]
mask =
1 0 1 0
primes(mask)
ans =
1 3
• the new vector is the length of the number of true values
• booleans may look like numbers when printed
but they are a different type
10Engineering Skills: programming in MATLABCIV1900
Index vectors can select elements in any order
• each element in the index vector selects an element
primes = [1 2 3 5 7 11 13];
indices = [1 6 4];
primes(indices)
ans =
1 11 5
• the index vector can be of any length
• the new vector has the same length as the index vector
• the index vector can be created using n:s:m range notation
• the special value end can be used in these ranges
11Engineering Skills: programming in MATLABCIV1900
Arrays can store many dimensions
• matrices are two dimensional arrays
• created with semi-colons to separate the rows:
x = [1 2 3; 4 5 6; 7 8 9]
x =
1 2 3
4 5 6
7 8 9
• accessed using a pair of indices (row first, then column)
x(1, 3)
ans =
3
• functions like zeros and ones work too
12Engineering Skills: programming in MATLABCIV1900
Functions apply to arrays in different ways
• some functions apply to all elements of an array
• e.g. min, max, sum, …
values = [0 5 -2];
sum(values)
ans =
3
• others apply to each element one at a time
• e.g. trig functions, absolute value (abs), …
abs(values)
ans =
0 5 2
13Engineering Skills: programming in MATLABCIV1900
Special operators exist for per element calculations
• the regular operators sometimes behave differently on arrays
• e.g. * does not multiply corresponding array elements
[1 2 3]*[4 5 6]
gives the error: Inner matrix dimensions must agree
• because * is matrix multiply (more about this in later weeks)
• we need array multiply which multiplies each pair of elements
to create a new array:
[1 2 3].*[4 5 6]
ans =
4 10 18
14Engineering Skills: programming in MATLABCIV1900
Concatenating and slicing matrices
15
>> a=[1 2 3; 5 7 9; 8 9 10]
>> b=[9 8 7; 6 5 4; 1 2 3]
• What would be the result?
>> c=[a b]
c = 1 2 3 9 8 7
5 7 9 6 5 4
8 9 10 1 2 3
>> d=[a; b]
d = 1 2 3
5 7 9
8 9 10
9 8 7
6 5 4
1 2 3
>> e=a(1,:)
e = 1 2 3
“1” means “the first row”
“:” means “all columns”
>> f=a(:,1)
f = 1
5
8
“:” means “all rows”
“1” means “the first column”
Engineering Skills: programming in MATLABCIV1900
Deleting rows and columns
16
• Easy, by using []
>>c
c = 1 2 3 9 8 7
5 7 9 6 5 4
8 9 10 1 2 3
• To delete the second column:
>> c(:,2)=[]
c = 1 3 9 8 7
5 9 6 5 4
8 10 1 2 3
• To further delete the second row:
>> c(2,:)=[]
c = 1 3 9 8 7
8 10 1 2 3
Engineering Skills: programming in MATLABCIV1900
17
Transpose of a matrix
17
• If a is a m x n matrix, then the transpose of a, denoted with a’,
is a n x m matrix whose first column is the first row of a, whose
second column is the second row of a, and so on
• In Matlab we can compute the transpose of a matrix using the
dot-apostrophe operator „
>>a=[1 2 3 4; 5 7 9 3; 8 9 10 12]
a = 1 2 3 4
5 7 9 3
8 9 10 12
>> a'
ans = 1 5 8
2 7 9
3 9 10
4 3 12
3 x 4
4 x 3
Engineering Skills: programming in MATLABCIV1900
18
Generating basic matrices
18
• zeros() – all elements are 0
>> zeros(2,3)
ans = 0 0 0
0 0 0
• ones() – all elements are 1
>> ones(2,3)
ans = 1 1 1
1 1 1
• rand() – uniformly distributed
random elements from (0,1)
>> rand(2,3)
ans = 0.8147 0.1270 0.6324
0.9058 0.9134 0.0975
• eye() – identity matrix
>> eye(3)
>>ans =
1 0 0
0 1 0
0 0 1
>> eye(5)
ans =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
CIV1900 Engineering Skills: programming in MATLAB
19
• Done element by element
• Matrices must have the same dimensions
>> a=[1,2,3; 5,7,9; 8,9,10]
a = 1 2 3
5 7 9
8 9 10
>> b=[9,8,7; 6,5,4; 1,2,3]
b = 9 8 7
6 5 4
1 2 3
• What would be the result?
>> c=a+b
c = 10 10 10
11 12 13
9 11 13
Adding and subtracting matrices
>> d=a-b
d = -8 -6 -4
-1 2 5
7 7 7
Engineering Skills: programming in MATLABCIV1900
20
• Each matrix element is multiplied by the scalar
>> a=[1,2,3; 5,7,9; 8,9,10]
a = 1 2 3
5 7 9
8 9 10
>> b=a*6
b = 6 12 18
30 42 54
48 54 60
• Do we need to use .* instead of * ?
Multiplying a matrix with a scalar
Engineering Skills: programming in MATLABCIV1900
Calculating the inverse matrix
• Let a, b and c are square matrices, a*b=c and
we are given a and c and need to find b
>> a=[9 2 7; 6 1 4; 1 6 3]
>> c=[1 2 3; 5 7 9; 8 9 10]
• Let‟s do it analytically:
21
• In Matlab we can use inv():
>> b=inv(a)*c
b = 5.9643 7.8214 9.6786
4.7857 5.9286 7.0714
-8.8929 -11.4643 -14.0357
cab
caaba
cab
1
1 1
multiply both sides on theleft by 1
a
, where I is the identity matrixIaa
1
Engineering Skills: programming in MATLABCIV1900
Matlab can manipulate not only numbers but also strings
• A character string or simply string is an ordered sequence of
characters (i.e. symbols and digits)
• In Matlab strings are enclosed in single quotes
>> s1 = 'Hello!'
s1 = Hello!
>> s2 = 'I am 20 years old.'
s2 = I am 20 years old.
• Single quotes can be included in the strings with double quotes
>> s4 = 'You''re smart'
s4 = You're smart
22Engineering Skills: programming in MATLABCIV1900
Matlab treats strings as arrays of characters
• We can apply the vector manipulation functions
• What is the result?
>> s1 = 'James';
>> size(s1)
ans = 1 5
>> length(s1)
ans = 5
>> s1(3)
ans = m
>> s1(6)
??? Attempted to access s1(6); index out of bounds
because numel(s1)=5.
23Engineering Skills: programming in MATLABCIV1900
Displaying string variables with disp()
• We already have seen how to use disp()
• num2str() must be used to convert numbers intro strings,
which are then concatenated with other strings in disp()
>> disp(6)
6
>> disp(['My favourite number is ', a])
My favourite number is
>> disp(['My favourite number is ', int2str(a)])
My favourite number is 6
24Engineering Skills: programming in MATLABCIV1900
Displaying string variables with fprintf()
• There are other display and print functions which do not require
numbers to be converted to strings to display information, e.g.
fprintf()
>> fprintf('My favourite number is %d n', a);
My favourite number is 6
%d – print the value of the variable a as an integer
n – the cursor goes to a new line
Other useful formatting symbols:
%f – float point number
%s – string
t – insert tab
2525Engineering Skills: programming in MATLABCIV1900

More Related Content

What's hot

Hamiltonian path
Hamiltonian pathHamiltonian path
Hamiltonian path
Arindam Ghosh
 
MATLAB - Arrays and Matrices
MATLAB - Arrays and MatricesMATLAB - Arrays and Matrices
MATLAB - Arrays and Matrices
Shameer Ahmed Koya
 
Extensible hashing
Extensible hashingExtensible hashing
Extensible hashing
rajshreemuthiah
 
MATLAB Programming
MATLAB Programming MATLAB Programming
MATLAB Programming
محمدعبد الحى
 
Matlab Basic Tutorial
Matlab Basic TutorialMatlab Basic Tutorial
Matlab Basic Tutorial
Muhammad Rizwan
 
Matlab
MatlabMatlab
Matlab
sandhya jois
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
BilawalBaloch1
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginners
Murshida ck
 
Spanning trees
Spanning treesSpanning trees
Spanning trees
Shareb Ismaeel
 
Master method
Master method Master method
Master method
Rajendran
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notationsNikhil Sharma
 
Interfacing memory with 8086 microprocessor
Interfacing memory with 8086 microprocessorInterfacing memory with 8086 microprocessor
Interfacing memory with 8086 microprocessor
Vikas Gupta
 
Matlab plotting
Matlab plottingMatlab plotting
Matlab plotting
shahid sultan
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
Ravikiran A
 
Gradient descent method
Gradient descent methodGradient descent method
Gradient descent method
Sanghyuk Chun
 
fuzzy fuzzification and defuzzification
fuzzy fuzzification and defuzzificationfuzzy fuzzification and defuzzification
fuzzy fuzzification and defuzzification
Nourhan Selem Salm
 
String operation
String operationString operation
String operation
Shakila Mahjabin
 
Birch Algorithm With Solved Example
Birch Algorithm With Solved ExampleBirch Algorithm With Solved Example
Birch Algorithm With Solved Example
kailash shaw
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applicationsTech_MX
 
Neural Networks: Radial Bases Functions (RBF)
Neural Networks: Radial Bases Functions (RBF)Neural Networks: Radial Bases Functions (RBF)
Neural Networks: Radial Bases Functions (RBF)
Mostafa G. M. Mostafa
 

What's hot (20)

Hamiltonian path
Hamiltonian pathHamiltonian path
Hamiltonian path
 
MATLAB - Arrays and Matrices
MATLAB - Arrays and MatricesMATLAB - Arrays and Matrices
MATLAB - Arrays and Matrices
 
Extensible hashing
Extensible hashingExtensible hashing
Extensible hashing
 
MATLAB Programming
MATLAB Programming MATLAB Programming
MATLAB Programming
 
Matlab Basic Tutorial
Matlab Basic TutorialMatlab Basic Tutorial
Matlab Basic Tutorial
 
Matlab
MatlabMatlab
Matlab
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginners
 
Spanning trees
Spanning treesSpanning trees
Spanning trees
 
Master method
Master method Master method
Master method
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notations
 
Interfacing memory with 8086 microprocessor
Interfacing memory with 8086 microprocessorInterfacing memory with 8086 microprocessor
Interfacing memory with 8086 microprocessor
 
Matlab plotting
Matlab plottingMatlab plotting
Matlab plotting
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
Gradient descent method
Gradient descent methodGradient descent method
Gradient descent method
 
fuzzy fuzzification and defuzzification
fuzzy fuzzification and defuzzificationfuzzy fuzzification and defuzzification
fuzzy fuzzification and defuzzification
 
String operation
String operationString operation
String operation
 
Birch Algorithm With Solved Example
Birch Algorithm With Solved ExampleBirch Algorithm With Solved Example
Birch Algorithm With Solved Example
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applications
 
Neural Networks: Radial Bases Functions (RBF)
Neural Networks: Radial Bases Functions (RBF)Neural Networks: Radial Bases Functions (RBF)
Neural Networks: Radial Bases Functions (RBF)
 

Viewers also liked

CIV1900 Matlab - Plotting & Coursework
CIV1900 Matlab - Plotting & CourseworkCIV1900 Matlab - Plotting & Coursework
CIV1900 Matlab - Plotting & CourseworkTUOS-Sam
 
Loops in matlab
Loops in matlabLoops in matlab
Loops in matlabTUOS-Sam
 
R Programming: Numeric Functions In R
R Programming: Numeric Functions In RR Programming: Numeric Functions In R
R Programming: Numeric Functions In R
Rsquared Academy
 
metode numerik stepest descent dengan rerata aritmatika
metode numerik stepest descent dengan rerata aritmatikametode numerik stepest descent dengan rerata aritmatika
metode numerik stepest descent dengan rerata aritmatika
Sabarinsyah Piliang
 
Introduction to Matlab Scripts
Introduction to Matlab ScriptsIntroduction to Matlab Scripts
Introduction to Matlab Scripts
Shameer Ahmed Koya
 
Modul1 metode bagi dua Praktikum Metode Numerik
Modul1 metode bagi dua Praktikum Metode NumerikModul1 metode bagi dua Praktikum Metode Numerik
Modul1 metode bagi dua Praktikum Metode Numerik
James Montolalu
 
Modul2 metode regula falsi praktikum metode numerik
Modul2 metode regula falsi praktikum metode numerikModul2 metode regula falsi praktikum metode numerik
Modul2 metode regula falsi praktikum metode numerik
James Montolalu
 
User defined Functions in MATLAB Part 1
User defined Functions in MATLAB Part 1User defined Functions in MATLAB Part 1
User defined Functions in MATLAB Part 1
Shameer Ahmed Koya
 
User Defined Functions in MATLAB Part-4
User Defined Functions in MATLAB Part-4User Defined Functions in MATLAB Part-4
User Defined Functions in MATLAB Part-4
Shameer Ahmed Koya
 
Metode numerik-buku-ajar-unila
Metode numerik-buku-ajar-unilaMetode numerik-buku-ajar-unila
Metode numerik-buku-ajar-unila
Ibad Ahmad
 
Matlab 1 level_1
Matlab 1 level_1Matlab 1 level_1
Matlab 1 level_1
Ahmed Farouk
 
Band Combination of Landsat 8 Earth-observing Satellite Images
Band Combination of Landsat 8 Earth-observing Satellite ImagesBand Combination of Landsat 8 Earth-observing Satellite Images
Band Combination of Landsat 8 Earth-observing Satellite Images
Kabir Uddin
 
MATLAB Programming - Loop Control Part 2
MATLAB Programming - Loop Control Part 2MATLAB Programming - Loop Control Part 2
MATLAB Programming - Loop Control Part 2
Shameer Ahmed Koya
 
mat lab introduction and basics to learn
mat lab introduction and basics to learnmat lab introduction and basics to learn
mat lab introduction and basics to learn
pavan373
 
Panduan matlab
Panduan matlabPanduan matlab
Panduan matlab
giya12001
 
Metode numerik persamaan non linier
Metode numerik persamaan non linierMetode numerik persamaan non linier
Metode numerik persamaan non linier
Izhan Nassuha
 
Contoh program matlab
Contoh program matlabContoh program matlab
Contoh program matlabZahra Doangs
 
4 Menggambar Grafik Fungsi Dengan Matlab
4 Menggambar Grafik Fungsi Dengan Matlab4 Menggambar Grafik Fungsi Dengan Matlab
4 Menggambar Grafik Fungsi Dengan Matlab
Simon Patabang
 

Viewers also liked (20)

CIV1900 Matlab - Plotting & Coursework
CIV1900 Matlab - Plotting & CourseworkCIV1900 Matlab - Plotting & Coursework
CIV1900 Matlab - Plotting & Coursework
 
Loops in matlab
Loops in matlabLoops in matlab
Loops in matlab
 
R Programming: Numeric Functions In R
R Programming: Numeric Functions In RR Programming: Numeric Functions In R
R Programming: Numeric Functions In R
 
Matlab time series example
Matlab time series exampleMatlab time series example
Matlab time series example
 
metode numerik stepest descent dengan rerata aritmatika
metode numerik stepest descent dengan rerata aritmatikametode numerik stepest descent dengan rerata aritmatika
metode numerik stepest descent dengan rerata aritmatika
 
Introduction to Matlab Scripts
Introduction to Matlab ScriptsIntroduction to Matlab Scripts
Introduction to Matlab Scripts
 
Modul1 metode bagi dua Praktikum Metode Numerik
Modul1 metode bagi dua Praktikum Metode NumerikModul1 metode bagi dua Praktikum Metode Numerik
Modul1 metode bagi dua Praktikum Metode Numerik
 
Modul2 metode regula falsi praktikum metode numerik
Modul2 metode regula falsi praktikum metode numerikModul2 metode regula falsi praktikum metode numerik
Modul2 metode regula falsi praktikum metode numerik
 
User defined Functions in MATLAB Part 1
User defined Functions in MATLAB Part 1User defined Functions in MATLAB Part 1
User defined Functions in MATLAB Part 1
 
Fungsi grafik di matlab
Fungsi grafik di matlabFungsi grafik di matlab
Fungsi grafik di matlab
 
User Defined Functions in MATLAB Part-4
User Defined Functions in MATLAB Part-4User Defined Functions in MATLAB Part-4
User Defined Functions in MATLAB Part-4
 
Metode numerik-buku-ajar-unila
Metode numerik-buku-ajar-unilaMetode numerik-buku-ajar-unila
Metode numerik-buku-ajar-unila
 
Matlab 1 level_1
Matlab 1 level_1Matlab 1 level_1
Matlab 1 level_1
 
Band Combination of Landsat 8 Earth-observing Satellite Images
Band Combination of Landsat 8 Earth-observing Satellite ImagesBand Combination of Landsat 8 Earth-observing Satellite Images
Band Combination of Landsat 8 Earth-observing Satellite Images
 
MATLAB Programming - Loop Control Part 2
MATLAB Programming - Loop Control Part 2MATLAB Programming - Loop Control Part 2
MATLAB Programming - Loop Control Part 2
 
mat lab introduction and basics to learn
mat lab introduction and basics to learnmat lab introduction and basics to learn
mat lab introduction and basics to learn
 
Panduan matlab
Panduan matlabPanduan matlab
Panduan matlab
 
Metode numerik persamaan non linier
Metode numerik persamaan non linierMetode numerik persamaan non linier
Metode numerik persamaan non linier
 
Contoh program matlab
Contoh program matlabContoh program matlab
Contoh program matlab
 
4 Menggambar Grafik Fungsi Dengan Matlab
4 Menggambar Grafik Fungsi Dengan Matlab4 Menggambar Grafik Fungsi Dengan Matlab
4 Menggambar Grafik Fungsi Dengan Matlab
 

Similar to Variables in matlab

Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
Satish Gummadi
 
Introduction to Matlab - Basic Functions
Introduction to Matlab - Basic FunctionsIntroduction to Matlab - Basic Functions
Introduction to Matlab - Basic Functions
joellivz
 
COMPANION TO MATRICES SESSION II.pptx
COMPANION TO MATRICES SESSION II.pptxCOMPANION TO MATRICES SESSION II.pptx
COMPANION TO MATRICES SESSION II.pptx
imman gwu
 
Matlab Tutorial.ppt
Matlab Tutorial.pptMatlab Tutorial.ppt
Matlab Tutorial.ppt
RaviMuthamala1
 
Matlab-1.pptx
Matlab-1.pptxMatlab-1.pptx
Matlab-1.pptx
aboma2hawi
 
Basic MATLAB-Presentation.pptx
Basic MATLAB-Presentation.pptxBasic MATLAB-Presentation.pptx
Basic MATLAB-Presentation.pptx
PremanandS3
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
chestialtaff
 
presentation.pptx
presentation.pptxpresentation.pptx
presentation.pptx
raghav415187
 
Introduction to Matlab.ppt
Introduction to Matlab.pptIntroduction to Matlab.ppt
Introduction to Matlab.ppt
Ravibabu Kancharla
 
Lines and planes in space
Lines and planes in spaceLines and planes in space
Lines and planes in space
Faizan Shabbir
 
Matlab-free course by Mohd Esa
Matlab-free course by Mohd EsaMatlab-free course by Mohd Esa
Matlab-free course by Mohd Esa
Mohd Esa
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
Vikash Jakhar
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
VidhyaSenthil
 
Matlab Tutorial for Beginners - I
Matlab Tutorial for Beginners - IMatlab Tutorial for Beginners - I
Matlab Tutorial for Beginners - I
Vijay Kumar Gupta
 
Introduction of MatLab
Introduction of MatLab Introduction of MatLab
Introduction of MatLab
Imran Nawaz
 
2. Chap 1.pptx
2. Chap 1.pptx2. Chap 1.pptx
2. Chap 1.pptx
HassanShah396906
 
Importance of matlab
Importance of matlabImportance of matlab
Importance of matlab
krajeshk1980
 
MATLAB for Technical Computing
MATLAB for Technical ComputingMATLAB for Technical Computing
MATLAB for Technical Computing
Naveed Rehman
 
CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdf
UmarMustafa13
 
Mat lab workshop
Mat lab workshopMat lab workshop
Mat lab workshop
Vinay Kumar
 

Similar to Variables in matlab (20)

Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
 
Introduction to Matlab - Basic Functions
Introduction to Matlab - Basic FunctionsIntroduction to Matlab - Basic Functions
Introduction to Matlab - Basic Functions
 
COMPANION TO MATRICES SESSION II.pptx
COMPANION TO MATRICES SESSION II.pptxCOMPANION TO MATRICES SESSION II.pptx
COMPANION TO MATRICES SESSION II.pptx
 
Matlab Tutorial.ppt
Matlab Tutorial.pptMatlab Tutorial.ppt
Matlab Tutorial.ppt
 
Matlab-1.pptx
Matlab-1.pptxMatlab-1.pptx
Matlab-1.pptx
 
Basic MATLAB-Presentation.pptx
Basic MATLAB-Presentation.pptxBasic MATLAB-Presentation.pptx
Basic MATLAB-Presentation.pptx
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
 
presentation.pptx
presentation.pptxpresentation.pptx
presentation.pptx
 
Introduction to Matlab.ppt
Introduction to Matlab.pptIntroduction to Matlab.ppt
Introduction to Matlab.ppt
 
Lines and planes in space
Lines and planes in spaceLines and planes in space
Lines and planes in space
 
Matlab-free course by Mohd Esa
Matlab-free course by Mohd EsaMatlab-free course by Mohd Esa
Matlab-free course by Mohd Esa
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Matlab Tutorial for Beginners - I
Matlab Tutorial for Beginners - IMatlab Tutorial for Beginners - I
Matlab Tutorial for Beginners - I
 
Introduction of MatLab
Introduction of MatLab Introduction of MatLab
Introduction of MatLab
 
2. Chap 1.pptx
2. Chap 1.pptx2. Chap 1.pptx
2. Chap 1.pptx
 
Importance of matlab
Importance of matlabImportance of matlab
Importance of matlab
 
MATLAB for Technical Computing
MATLAB for Technical ComputingMATLAB for Technical Computing
MATLAB for Technical Computing
 
CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdf
 
Mat lab workshop
Mat lab workshopMat lab workshop
Mat lab workshop
 

Variables in matlab

  • 2. Variables allow you to store (intermediate) results • a variable is a named location in computer memory • for storing/retrieving one or more values • created in MATLAB by assignment radius = 3 • accessed by mentioning the name (or in Workspace) >>radius radius = 3 • can be used anywhere a number (literal) can be used area = pi*radius^2 CIV1900 Engineering Skills: programming in MATLAB 2
  • 3. Variables in MATLAB • variables are listed in alphabetical order in the Workspace • with information about their name, size, type and min/max • not all information is shown automatically • use View > Choose Columns when focus is in the Workspace • MATLAB automatically creates a variable called ans if needed: >> 1024^3/8 ans= 134217728 • If you don't want to print out the result add a semi-colon >> diameter = 2*radius; 3Engineering Skills: programming in MATLABCIV1900
  • 4. Assignment might look like algebra, but it isn't • x = x + 1 doesn't sound right • how can x be equal to x + 1 • why isn't it a logical inconsistency? • because assignment isn't equality at all • assignment is a two step process: • calculate the value on the right hand side (r-value) • store the result in the variable on the left hand side (l-value) • So x = x + 1 means: • evaluate x + 1 first by getting the value out of variable x • store the result back into variable x 4Engineering Skills: programming in MATLABCIV1900
  • 5. MATLAB arrays are collections of (like) values • arrays store multiple elements of one type • each element can be accessed by position in the array • called indexing or subscripting the array • uses the array name and then the index in parentheses • most other programming languages index from 0 5Engineering Skills: programming in MATLABCIV1900
  • 6. 1-dimensional arrays are called vectors • created with square brackets and (optional) commas pos = [1, 0, -1] primes = [1 2 3 5 7 11 13] • accessed with indices e.g. the 6th prime number is? primes(6) ans = 11 • notice how vectors appear in the Workspace (e.g. size 1x7) 6Engineering Skills: programming in MATLABCIV1900
  • 7. Vectors can be created using n:s:m notation • vectors ranging from n to m with step s can be written n:s:m e.g. from 1 to 20 stepping by 3: x = 1:3:20 x = 1 4 7 10 13 16 19 • if the step size is missing, the default is 1: x = 1:7 x = 1 2 3 4 5 6 7 • the vector goes up to and including the last value • think about what might happen with negative values! 7Engineering Skills: programming in MATLABCIV1900
  • 8. MATLAB has functions to create vectors with fixed sizes • linspace takes a n and m, and a number of elements: • e.g. create a vector from 0 to 3 containing 5 values linspace(0, 3, 5) ans = 0 0.7500 1.5000 2.2500 3.0000 • zeros and ones create vectors of only zeros and ones zeros(1, 5) ans = 0 0 0 0 0 ones(1, 5) ans = 1 1 1 1 1 8Engineering Skills: programming in MATLABCIV1900
  • 9. Indexing is used to make vectors longer or shorter • assigning to an index beyond the length grows the vector data = [1 2 3]; data(6) = -1 data = 1 2 3 0 0 -1 • zeros are used to fill in the gaps • assigning an empty vector to an index removes elements data(2) = [] data = 1 3 0 0 -1 9Engineering Skills: programming in MATLABCIV1900
  • 10. Boolean vectors can be used to select elements • booleans are true/false (that is, yes/no values) of type logical primes = [1 2 3 5 7 11 13]; mask = [true false true false] mask = 1 0 1 0 primes(mask) ans = 1 3 • the new vector is the length of the number of true values • booleans may look like numbers when printed but they are a different type 10Engineering Skills: programming in MATLABCIV1900
  • 11. Index vectors can select elements in any order • each element in the index vector selects an element primes = [1 2 3 5 7 11 13]; indices = [1 6 4]; primes(indices) ans = 1 11 5 • the index vector can be of any length • the new vector has the same length as the index vector • the index vector can be created using n:s:m range notation • the special value end can be used in these ranges 11Engineering Skills: programming in MATLABCIV1900
  • 12. Arrays can store many dimensions • matrices are two dimensional arrays • created with semi-colons to separate the rows: x = [1 2 3; 4 5 6; 7 8 9] x = 1 2 3 4 5 6 7 8 9 • accessed using a pair of indices (row first, then column) x(1, 3) ans = 3 • functions like zeros and ones work too 12Engineering Skills: programming in MATLABCIV1900
  • 13. Functions apply to arrays in different ways • some functions apply to all elements of an array • e.g. min, max, sum, … values = [0 5 -2]; sum(values) ans = 3 • others apply to each element one at a time • e.g. trig functions, absolute value (abs), … abs(values) ans = 0 5 2 13Engineering Skills: programming in MATLABCIV1900
  • 14. Special operators exist for per element calculations • the regular operators sometimes behave differently on arrays • e.g. * does not multiply corresponding array elements [1 2 3]*[4 5 6] gives the error: Inner matrix dimensions must agree • because * is matrix multiply (more about this in later weeks) • we need array multiply which multiplies each pair of elements to create a new array: [1 2 3].*[4 5 6] ans = 4 10 18 14Engineering Skills: programming in MATLABCIV1900
  • 15. Concatenating and slicing matrices 15 >> a=[1 2 3; 5 7 9; 8 9 10] >> b=[9 8 7; 6 5 4; 1 2 3] • What would be the result? >> c=[a b] c = 1 2 3 9 8 7 5 7 9 6 5 4 8 9 10 1 2 3 >> d=[a; b] d = 1 2 3 5 7 9 8 9 10 9 8 7 6 5 4 1 2 3 >> e=a(1,:) e = 1 2 3 “1” means “the first row” “:” means “all columns” >> f=a(:,1) f = 1 5 8 “:” means “all rows” “1” means “the first column” Engineering Skills: programming in MATLABCIV1900
  • 16. Deleting rows and columns 16 • Easy, by using [] >>c c = 1 2 3 9 8 7 5 7 9 6 5 4 8 9 10 1 2 3 • To delete the second column: >> c(:,2)=[] c = 1 3 9 8 7 5 9 6 5 4 8 10 1 2 3 • To further delete the second row: >> c(2,:)=[] c = 1 3 9 8 7 8 10 1 2 3 Engineering Skills: programming in MATLABCIV1900
  • 17. 17 Transpose of a matrix 17 • If a is a m x n matrix, then the transpose of a, denoted with a’, is a n x m matrix whose first column is the first row of a, whose second column is the second row of a, and so on • In Matlab we can compute the transpose of a matrix using the dot-apostrophe operator „ >>a=[1 2 3 4; 5 7 9 3; 8 9 10 12] a = 1 2 3 4 5 7 9 3 8 9 10 12 >> a' ans = 1 5 8 2 7 9 3 9 10 4 3 12 3 x 4 4 x 3 Engineering Skills: programming in MATLABCIV1900
  • 18. 18 Generating basic matrices 18 • zeros() – all elements are 0 >> zeros(2,3) ans = 0 0 0 0 0 0 • ones() – all elements are 1 >> ones(2,3) ans = 1 1 1 1 1 1 • rand() – uniformly distributed random elements from (0,1) >> rand(2,3) ans = 0.8147 0.1270 0.6324 0.9058 0.9134 0.0975 • eye() – identity matrix >> eye(3) >>ans = 1 0 0 0 1 0 0 0 1 >> eye(5) ans = 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 CIV1900 Engineering Skills: programming in MATLAB
  • 19. 19 • Done element by element • Matrices must have the same dimensions >> a=[1,2,3; 5,7,9; 8,9,10] a = 1 2 3 5 7 9 8 9 10 >> b=[9,8,7; 6,5,4; 1,2,3] b = 9 8 7 6 5 4 1 2 3 • What would be the result? >> c=a+b c = 10 10 10 11 12 13 9 11 13 Adding and subtracting matrices >> d=a-b d = -8 -6 -4 -1 2 5 7 7 7 Engineering Skills: programming in MATLABCIV1900
  • 20. 20 • Each matrix element is multiplied by the scalar >> a=[1,2,3; 5,7,9; 8,9,10] a = 1 2 3 5 7 9 8 9 10 >> b=a*6 b = 6 12 18 30 42 54 48 54 60 • Do we need to use .* instead of * ? Multiplying a matrix with a scalar Engineering Skills: programming in MATLABCIV1900
  • 21. Calculating the inverse matrix • Let a, b and c are square matrices, a*b=c and we are given a and c and need to find b >> a=[9 2 7; 6 1 4; 1 6 3] >> c=[1 2 3; 5 7 9; 8 9 10] • Let‟s do it analytically: 21 • In Matlab we can use inv(): >> b=inv(a)*c b = 5.9643 7.8214 9.6786 4.7857 5.9286 7.0714 -8.8929 -11.4643 -14.0357 cab caaba cab 1 1 1 multiply both sides on theleft by 1 a , where I is the identity matrixIaa 1 Engineering Skills: programming in MATLABCIV1900
  • 22. Matlab can manipulate not only numbers but also strings • A character string or simply string is an ordered sequence of characters (i.e. symbols and digits) • In Matlab strings are enclosed in single quotes >> s1 = 'Hello!' s1 = Hello! >> s2 = 'I am 20 years old.' s2 = I am 20 years old. • Single quotes can be included in the strings with double quotes >> s4 = 'You''re smart' s4 = You're smart 22Engineering Skills: programming in MATLABCIV1900
  • 23. Matlab treats strings as arrays of characters • We can apply the vector manipulation functions • What is the result? >> s1 = 'James'; >> size(s1) ans = 1 5 >> length(s1) ans = 5 >> s1(3) ans = m >> s1(6) ??? Attempted to access s1(6); index out of bounds because numel(s1)=5. 23Engineering Skills: programming in MATLABCIV1900
  • 24. Displaying string variables with disp() • We already have seen how to use disp() • num2str() must be used to convert numbers intro strings, which are then concatenated with other strings in disp() >> disp(6) 6 >> disp(['My favourite number is ', a]) My favourite number is >> disp(['My favourite number is ', int2str(a)]) My favourite number is 6 24Engineering Skills: programming in MATLABCIV1900
  • 25. Displaying string variables with fprintf() • There are other display and print functions which do not require numbers to be converted to strings to display information, e.g. fprintf() >> fprintf('My favourite number is %d n', a); My favourite number is 6 %d – print the value of the variable a as an integer n – the cursor goes to a new line Other useful formatting symbols: %f – float point number %s – string t – insert tab 2525Engineering Skills: programming in MATLABCIV1900