SlideShare a Scribd company logo
1 of 18
CSCI 101
Vectorized Code
Outline
• Operations on Vectors and Matrices
• Vectors and Matrices as Function Arguments
• Logical Vectors
Operations on Vectors and Matrices
v=[3 7 2 1]
for i = 1:length(v)
v(i) =v(i) * 3;
end
v= [3 7 2 1];
>> v=v*3
9 27 6 3
mat = [4:6; 3:-1:1]
mat =
4 5 6
3 2 1
>> mat * 2
ans =
8 10 12
6 4 2
Scalar Operations
Operation Algebraic Form MATLAB Form
Addition a + b a + b
Subtraction a – b a – b
Multiplication a × b a * b
Division
a
b
a / b
Exponentiation ab a ^ b
Same operators can be applied to arrays following linear algebra rules.
These rules are specific to each operation
A+B (A and B should have same size)
A*B (A columns should equal B rows)
A^B (A should be squared matrix)
A/B = A* B-1 (B should be invertible and A columns should be equal B-1 rows )
Element Operations
Both arrays must have the same number of rows and columns
A + B = [1 2 3] + [3 4 5] = [4 6 8]
Element and Algebraic operations are the same
A .* B = [1 2 3] .* [3 4 5] = [3 8 15]
A .^ B = [4 9 6] .^ [2 2 2] = [16 81 36]
A ./ B =[4 9 6] ./ [2 3 2] = [2 3 3]
Array Operations
Operation MATLAB form Comments
Addition a + b Adds each element in a to the element with the same
index in b
Subtraction a – b Subtracts from each element in a the element with the
same index in b
Multiplication a .* b Multiplies each element in a with the element in b
having the same index
Either a or b can be a scalar
Right Division a ./ b Element by element division of a and b:
a(i,j) / b(i,j) provided a, b have same shape
Either a or b can be a scalar
Left Division a . b Element by element division of a and b:
b(i,j) / a(i,j) provided a, b have same shape
Either a or b can be a scalar
Exponentiation a .^ b Element by element exponentiation of a and b:
a(i,j) ^ b(i,j) provided a, b have same shape
Either a or b can be a scalar
Operations Rules Examples
v=[3 7 2 1];
>> v ^ 2
??? Error using ==> mpower
Inputs must be a scalar and a square matrix.
To compute elementwise POWER, use POWER (.^)
instead.
>> v .^ 2
ans =
9 49 4 1
Operations Rules Examples
v1 = 2:5;
 v1 = [2 3 4 5]
v2 = [33 11 5 1];
>> v1 * v2 %Error why
>> v1*v2’ % what is the output
>> v1 .* v2 % v1 and v2 must have same size
Vectors and Matrices as Function
Arguments
• Many functions accept scalars as input
• Some functions work on arrays
• Most scalar functions accept arrays as well
– The function is performed on each element in the array
individually
• Try x = pi/2; y = sin(x) in MATLAB
• Now try
x = [0 pi/2 pi 3*pi/2 2*pi];
y = sin(x)
Functions Examples
v1=[1 3 2 7 4 -2]
v2=[5 3 4 1 2 -2]
[mx mxi]=max(v1)  7 4
v=v1-v2 -4 0 -2 6 2 0
v=sign(v1-v2) -1 0 -1 1 1 0
x=sum(v1)  15
v=find(v1>3)  4 5
Logical Vectors
v1=[1 3 2 7 4 -2]
v2=[5 3 -4 -1 2 -2]
v=v1>0  1 1 1 1 1 0
v=v2>0 1 1 0 0 1 0
a=v2(v2>0) 5 3 2
x=sum(v2>0) 3
v=true(1,5)  1 1 1 1 1
v=false(1,5)  0 0 0 0 0
x=all(v1>0)  1 (are all ones?)
y=any(v1>0)  0 (any one?)
Example
?)0:),1((ofvaluetheisWhat
5310
2412
3142
0311

















 aBaLet
B = [0 0 0 1]
Example
?)2:1],34([ofvaluetheisWhat
5310
2412
3142
0311
aDaLet 





















 

12
10
D
Example
Write a program using Matlab loop(s) to calculate the following
while assuming that the variable x has been initialized:
𝑆 =
𝑖=1
10
𝑥𝑖
2
N=10;
x = 1:N;
S=0;
for i = 1:N
S=S+ x(i)*x(i);
end
S
Vectorize your code S=sum(x.*x)
Getting Maximum and Minimum Value
v=[1 3 2 7 4 2]
maxv=0;
for =1:length(v)
if v(i)>maxv
maxv=v(i);
maxi=i;
end
end
% Repeat for the minimum
i v(i) maxv maxi
1 1 01 ?1
2 3 13 12
3 2 3 2
4 7 37 24
5 4 7 4
6 2 7 4
Vectorize your code: [maxv maxi]=max(v)
Example
Counting Elements
v=[1 3 2 -7 4 -2]
c=0;
for =1:length(v)
if v(i)>0
c=c+1;
end
end
% Repeat for the negative
i v(i) c
1 1 01
2 3 12
3 2 23
4 -7 3
5 4 34
6 -2 4
Vectorize your code c = sum(v>0)
Example
Comparing Elements
v1=[1 3 2 7 4 -2]
v2=[5 3 4 1 2 -2]
for i=1:length(v1)
if v1(i)>v2(i)
v(i)=1;
else
v(i)=0;
end
end
i v1(i) v2(i) v(i)
1 1 5 0
2 3 3 0
3 2 4 0
4 7 1 1
5 4 2 1
6 -2 -2 0
Vectorize your code: v= v1>v2
Example
Vertical Motion
% Vertical motion under gravity
g = 9.81; % acceleration due to gravity
u = 60; % initial velocity in metres/sec
t = 0 : 0.1 : 12.3; % time in seconds
s = u * t – g / 2 * t .ˆ 2; % vertical displacement in metres
plot(t, s), title( ’Vertical motion under gravity’ )
xlabel( ’time’ ), ylabel( ’vertical displacement’ )
grid
disp( [t’ s’] ) % display a table
Example

More Related Content

What's hot

Variables in matlab
Variables in matlabVariables in matlab
Variables in matlabTUOS-Sam
 
Matrix Multiplication(An example of concurrent programming)
Matrix Multiplication(An example of concurrent programming)Matrix Multiplication(An example of concurrent programming)
Matrix Multiplication(An example of concurrent programming)Pramit Kumar
 
Matlab matrices and arrays
Matlab matrices and arraysMatlab matrices and arrays
Matlab matrices and arraysAmeen San
 
Non linear curve fitting
Non linear curve fitting Non linear curve fitting
Non linear curve fitting Anumita Mondal
 
Solution of matlab chapter 4
Solution of matlab chapter 4Solution of matlab chapter 4
Solution of matlab chapter 4AhsanIrshad8
 
Waldie pd2
Waldie pd2Waldie pd2
Waldie pd2guero456
 
SKuehn_MachineLearningAndOptimization_2015
SKuehn_MachineLearningAndOptimization_2015SKuehn_MachineLearningAndOptimization_2015
SKuehn_MachineLearningAndOptimization_2015Stefan Kühn
 
Kim Modelling Functions
Kim Modelling FunctionsKim Modelling Functions
Kim Modelling Functionscoburgmaths
 
case study of curve fitting
case study of curve fittingcase study of curve fitting
case study of curve fittingAdarsh Patel
 

What's hot (18)

Variables in matlab
Variables in matlabVariables in matlab
Variables in matlab
 
Matrix Multiplication(An example of concurrent programming)
Matrix Multiplication(An example of concurrent programming)Matrix Multiplication(An example of concurrent programming)
Matrix Multiplication(An example of concurrent programming)
 
Matlab matrices and arrays
Matlab matrices and arraysMatlab matrices and arrays
Matlab matrices and arrays
 
Non linear curve fitting
Non linear curve fitting Non linear curve fitting
Non linear curve fitting
 
Solution of matlab chapter 4
Solution of matlab chapter 4Solution of matlab chapter 4
Solution of matlab chapter 4
 
R nonlinear least square
R   nonlinear least squareR   nonlinear least square
R nonlinear least square
 
Mc
McMc
Mc
 
Waldie pd2
Waldie pd2Waldie pd2
Waldie pd2
 
SKuehn_MachineLearningAndOptimization_2015
SKuehn_MachineLearningAndOptimization_2015SKuehn_MachineLearningAndOptimization_2015
SKuehn_MachineLearningAndOptimization_2015
 
1. vectors
1. vectors1. vectors
1. vectors
 
MATLAB - Arrays and Matrices
MATLAB - Arrays and MatricesMATLAB - Arrays and Matrices
MATLAB - Arrays and Matrices
 
Fourier Transform Assignment Help
Fourier Transform Assignment HelpFourier Transform Assignment Help
Fourier Transform Assignment Help
 
Greedy
GreedyGreedy
Greedy
 
Hw11 v1
Hw11 v1Hw11 v1
Hw11 v1
 
gmrit-cse
gmrit-csegmrit-cse
gmrit-cse
 
Kim Modelling Functions
Kim Modelling FunctionsKim Modelling Functions
Kim Modelling Functions
 
case study of curve fitting
case study of curve fittingcase study of curve fitting
case study of curve fitting
 
Basic concepts in_matlab
Basic concepts in_matlabBasic concepts in_matlab
Basic concepts in_matlab
 

Similar to Csci101 lect09 vectorized_code

INTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptxINTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptxDevaraj Chilakala
 
Basic MATLAB-Presentation.pptx
Basic MATLAB-Presentation.pptxBasic MATLAB-Presentation.pptx
Basic MATLAB-Presentation.pptxPremanandS3
 
Bra and ket notations
Bra and ket notationsBra and ket notations
Bra and ket notationsJoel Joel
 
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docxMATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docxandreecapon
 
Linear Algebra and Matlab tutorial
Linear Algebra and Matlab tutorialLinear Algebra and Matlab tutorial
Linear Algebra and Matlab tutorialJia-Bin Huang
 
Matlab_Simulink_Tutorial.ppt
Matlab_Simulink_Tutorial.pptMatlab_Simulink_Tutorial.ppt
Matlab_Simulink_Tutorial.pptPrasenjitDey49
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentationManchireddy Reddy
 
MATLAB-Introd.ppt
MATLAB-Introd.pptMATLAB-Introd.ppt
MATLAB-Introd.pptkebeAman
 
Lines and planes in space
Lines and planes in spaceLines and planes in space
Lines and planes in spaceFaizan Shabbir
 
8. Vectors data frames
8. Vectors data frames8. Vectors data frames
8. Vectors data framesExternalEvents
 
matrix algebra
matrix algebramatrix algebra
matrix algebrakganu
 
M01L01 Advance Engineering Mathematics.pptx
M01L01 Advance Engineering Mathematics.pptxM01L01 Advance Engineering Mathematics.pptx
M01L01 Advance Engineering Mathematics.pptxSaurabhKalita5
 
Matrix algebra in_r
Matrix algebra in_rMatrix algebra in_r
Matrix algebra in_rRazzaqe
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersMurshida ck
 
Introduction to matlab lecture 2 of 4
Introduction to matlab lecture 2 of 4Introduction to matlab lecture 2 of 4
Introduction to matlab lecture 2 of 4Randa Elanwar
 

Similar to Csci101 lect09 vectorized_code (20)

Lesson4.3Vectors.ppt
Lesson4.3Vectors.pptLesson4.3Vectors.ppt
Lesson4.3Vectors.ppt
 
INTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptxINTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptx
 
Basic MATLAB-Presentation.pptx
Basic MATLAB-Presentation.pptxBasic MATLAB-Presentation.pptx
Basic MATLAB-Presentation.pptx
 
Bra and ket notations
Bra and ket notationsBra and ket notations
Bra and ket notations
 
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docxMATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
 
Linear Algebra and Matlab tutorial
Linear Algebra and Matlab tutorialLinear Algebra and Matlab tutorial
Linear Algebra and Matlab tutorial
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
 
Matlab-1.pptx
Matlab-1.pptxMatlab-1.pptx
Matlab-1.pptx
 
presentation.pptx
presentation.pptxpresentation.pptx
presentation.pptx
 
Matlab_Simulink_Tutorial.ppt
Matlab_Simulink_Tutorial.pptMatlab_Simulink_Tutorial.ppt
Matlab_Simulink_Tutorial.ppt
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentation
 
MATLAB-Introd.ppt
MATLAB-Introd.pptMATLAB-Introd.ppt
MATLAB-Introd.ppt
 
Lines and planes in space
Lines and planes in spaceLines and planes in space
Lines and planes in space
 
8. Vectors data frames
8. Vectors data frames8. Vectors data frames
8. Vectors data frames
 
matrix algebra
matrix algebramatrix algebra
matrix algebra
 
Matlab
MatlabMatlab
Matlab
 
M01L01 Advance Engineering Mathematics.pptx
M01L01 Advance Engineering Mathematics.pptxM01L01 Advance Engineering Mathematics.pptx
M01L01 Advance Engineering Mathematics.pptx
 
Matrix algebra in_r
Matrix algebra in_rMatrix algebra in_r
Matrix algebra in_r
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginners
 
Introduction to matlab lecture 2 of 4
Introduction to matlab lecture 2 of 4Introduction to matlab lecture 2 of 4
Introduction to matlab lecture 2 of 4
 

More from Elsayed Hemayed

14 cie552 camera_calibration
14 cie552 camera_calibration14 cie552 camera_calibration
14 cie552 camera_calibrationElsayed Hemayed
 
12 cie552 object_recognition
12 cie552 object_recognition12 cie552 object_recognition
12 cie552 object_recognitionElsayed Hemayed
 
11 cie552 image_featuresii_sift
11 cie552 image_featuresii_sift11 cie552 image_featuresii_sift
11 cie552 image_featuresii_siftElsayed Hemayed
 
10 cie552 image_featuresii_corner
10 cie552 image_featuresii_corner10 cie552 image_featuresii_corner
10 cie552 image_featuresii_cornerElsayed Hemayed
 
09 cie552 image_featuresi
09 cie552 image_featuresi09 cie552 image_featuresi
09 cie552 image_featuresiElsayed Hemayed
 
08 cie552 image_segmentation
08 cie552 image_segmentation08 cie552 image_segmentation
08 cie552 image_segmentationElsayed Hemayed
 
07 cie552 image_mosaicing
07 cie552 image_mosaicing07 cie552 image_mosaicing
07 cie552 image_mosaicingElsayed Hemayed
 
06 cie552 image_manipulation
06 cie552 image_manipulation06 cie552 image_manipulation
06 cie552 image_manipulationElsayed Hemayed
 
05 cie552 image_enhancement
05 cie552 image_enhancement05 cie552 image_enhancement
05 cie552 image_enhancementElsayed Hemayed
 
04 cie552 image_filtering_frequency
04 cie552 image_filtering_frequency04 cie552 image_filtering_frequency
04 cie552 image_filtering_frequencyElsayed Hemayed
 
03 cie552 image_filtering_spatial
03 cie552 image_filtering_spatial03 cie552 image_filtering_spatial
03 cie552 image_filtering_spatialElsayed Hemayed
 
02 cie552 image_andcamera
02 cie552 image_andcamera02 cie552 image_andcamera
02 cie552 image_andcameraElsayed Hemayed
 
Csci101 lect04 advanced_selection
Csci101 lect04 advanced_selectionCsci101 lect04 advanced_selection
Csci101 lect04 advanced_selectionElsayed Hemayed
 
Csci101 lect10 algorithms_iii
Csci101 lect10 algorithms_iiiCsci101 lect10 algorithms_iii
Csci101 lect10 algorithms_iiiElsayed Hemayed
 
Csci101 lect08b matlab_programs
Csci101 lect08b matlab_programsCsci101 lect08b matlab_programs
Csci101 lect08b matlab_programsElsayed Hemayed
 
Csci101 lect08a matlab_programs
Csci101 lect08a matlab_programsCsci101 lect08a matlab_programs
Csci101 lect08a matlab_programsElsayed Hemayed
 
Csci101 lect07 algorithms_ii
Csci101 lect07 algorithms_iiCsci101 lect07 algorithms_ii
Csci101 lect07 algorithms_iiElsayed Hemayed
 
Csci101 lect06 advanced_looping
Csci101 lect06 advanced_loopingCsci101 lect06 advanced_looping
Csci101 lect06 advanced_loopingElsayed Hemayed
 
Csci101 lect05 formatted_output
Csci101 lect05 formatted_outputCsci101 lect05 formatted_output
Csci101 lect05 formatted_outputElsayed Hemayed
 

More from Elsayed Hemayed (20)

14 cie552 camera_calibration
14 cie552 camera_calibration14 cie552 camera_calibration
14 cie552 camera_calibration
 
12 cie552 object_recognition
12 cie552 object_recognition12 cie552 object_recognition
12 cie552 object_recognition
 
11 cie552 image_featuresii_sift
11 cie552 image_featuresii_sift11 cie552 image_featuresii_sift
11 cie552 image_featuresii_sift
 
10 cie552 image_featuresii_corner
10 cie552 image_featuresii_corner10 cie552 image_featuresii_corner
10 cie552 image_featuresii_corner
 
09 cie552 image_featuresi
09 cie552 image_featuresi09 cie552 image_featuresi
09 cie552 image_featuresi
 
08 cie552 image_segmentation
08 cie552 image_segmentation08 cie552 image_segmentation
08 cie552 image_segmentation
 
07 cie552 image_mosaicing
07 cie552 image_mosaicing07 cie552 image_mosaicing
07 cie552 image_mosaicing
 
06 cie552 image_manipulation
06 cie552 image_manipulation06 cie552 image_manipulation
06 cie552 image_manipulation
 
05 cie552 image_enhancement
05 cie552 image_enhancement05 cie552 image_enhancement
05 cie552 image_enhancement
 
04 cie552 image_filtering_frequency
04 cie552 image_filtering_frequency04 cie552 image_filtering_frequency
04 cie552 image_filtering_frequency
 
03 cie552 image_filtering_spatial
03 cie552 image_filtering_spatial03 cie552 image_filtering_spatial
03 cie552 image_filtering_spatial
 
02 cie552 image_andcamera
02 cie552 image_andcamera02 cie552 image_andcamera
02 cie552 image_andcamera
 
01 cie552 introduction
01 cie552 introduction01 cie552 introduction
01 cie552 introduction
 
Csci101 lect04 advanced_selection
Csci101 lect04 advanced_selectionCsci101 lect04 advanced_selection
Csci101 lect04 advanced_selection
 
Csci101 lect10 algorithms_iii
Csci101 lect10 algorithms_iiiCsci101 lect10 algorithms_iii
Csci101 lect10 algorithms_iii
 
Csci101 lect08b matlab_programs
Csci101 lect08b matlab_programsCsci101 lect08b matlab_programs
Csci101 lect08b matlab_programs
 
Csci101 lect08a matlab_programs
Csci101 lect08a matlab_programsCsci101 lect08a matlab_programs
Csci101 lect08a matlab_programs
 
Csci101 lect07 algorithms_ii
Csci101 lect07 algorithms_iiCsci101 lect07 algorithms_ii
Csci101 lect07 algorithms_ii
 
Csci101 lect06 advanced_looping
Csci101 lect06 advanced_loopingCsci101 lect06 advanced_looping
Csci101 lect06 advanced_looping
 
Csci101 lect05 formatted_output
Csci101 lect05 formatted_outputCsci101 lect05 formatted_output
Csci101 lect05 formatted_output
 

Recently uploaded

EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 

Recently uploaded (20)

EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 

Csci101 lect09 vectorized_code

  • 2. Outline • Operations on Vectors and Matrices • Vectors and Matrices as Function Arguments • Logical Vectors
  • 3. Operations on Vectors and Matrices v=[3 7 2 1] for i = 1:length(v) v(i) =v(i) * 3; end v= [3 7 2 1]; >> v=v*3 9 27 6 3 mat = [4:6; 3:-1:1] mat = 4 5 6 3 2 1 >> mat * 2 ans = 8 10 12 6 4 2
  • 4. Scalar Operations Operation Algebraic Form MATLAB Form Addition a + b a + b Subtraction a – b a – b Multiplication a × b a * b Division a b a / b Exponentiation ab a ^ b Same operators can be applied to arrays following linear algebra rules. These rules are specific to each operation A+B (A and B should have same size) A*B (A columns should equal B rows) A^B (A should be squared matrix) A/B = A* B-1 (B should be invertible and A columns should be equal B-1 rows )
  • 5. Element Operations Both arrays must have the same number of rows and columns A + B = [1 2 3] + [3 4 5] = [4 6 8] Element and Algebraic operations are the same A .* B = [1 2 3] .* [3 4 5] = [3 8 15] A .^ B = [4 9 6] .^ [2 2 2] = [16 81 36] A ./ B =[4 9 6] ./ [2 3 2] = [2 3 3]
  • 6. Array Operations Operation MATLAB form Comments Addition a + b Adds each element in a to the element with the same index in b Subtraction a – b Subtracts from each element in a the element with the same index in b Multiplication a .* b Multiplies each element in a with the element in b having the same index Either a or b can be a scalar Right Division a ./ b Element by element division of a and b: a(i,j) / b(i,j) provided a, b have same shape Either a or b can be a scalar Left Division a . b Element by element division of a and b: b(i,j) / a(i,j) provided a, b have same shape Either a or b can be a scalar Exponentiation a .^ b Element by element exponentiation of a and b: a(i,j) ^ b(i,j) provided a, b have same shape Either a or b can be a scalar
  • 7. Operations Rules Examples v=[3 7 2 1]; >> v ^ 2 ??? Error using ==> mpower Inputs must be a scalar and a square matrix. To compute elementwise POWER, use POWER (.^) instead. >> v .^ 2 ans = 9 49 4 1
  • 8. Operations Rules Examples v1 = 2:5;  v1 = [2 3 4 5] v2 = [33 11 5 1]; >> v1 * v2 %Error why >> v1*v2’ % what is the output >> v1 .* v2 % v1 and v2 must have same size
  • 9. Vectors and Matrices as Function Arguments • Many functions accept scalars as input • Some functions work on arrays • Most scalar functions accept arrays as well – The function is performed on each element in the array individually • Try x = pi/2; y = sin(x) in MATLAB • Now try x = [0 pi/2 pi 3*pi/2 2*pi]; y = sin(x)
  • 10. Functions Examples v1=[1 3 2 7 4 -2] v2=[5 3 4 1 2 -2] [mx mxi]=max(v1)  7 4 v=v1-v2 -4 0 -2 6 2 0 v=sign(v1-v2) -1 0 -1 1 1 0 x=sum(v1)  15 v=find(v1>3)  4 5
  • 11. Logical Vectors v1=[1 3 2 7 4 -2] v2=[5 3 -4 -1 2 -2] v=v1>0  1 1 1 1 1 0 v=v2>0 1 1 0 0 1 0 a=v2(v2>0) 5 3 2 x=sum(v2>0) 3 v=true(1,5)  1 1 1 1 1 v=false(1,5)  0 0 0 0 0 x=all(v1>0)  1 (are all ones?) y=any(v1>0)  0 (any one?)
  • 14. Example Write a program using Matlab loop(s) to calculate the following while assuming that the variable x has been initialized: 𝑆 = 𝑖=1 10 𝑥𝑖 2 N=10; x = 1:N; S=0; for i = 1:N S=S+ x(i)*x(i); end S Vectorize your code S=sum(x.*x)
  • 15. Getting Maximum and Minimum Value v=[1 3 2 7 4 2] maxv=0; for =1:length(v) if v(i)>maxv maxv=v(i); maxi=i; end end % Repeat for the minimum i v(i) maxv maxi 1 1 01 ?1 2 3 13 12 3 2 3 2 4 7 37 24 5 4 7 4 6 2 7 4 Vectorize your code: [maxv maxi]=max(v) Example
  • 16. Counting Elements v=[1 3 2 -7 4 -2] c=0; for =1:length(v) if v(i)>0 c=c+1; end end % Repeat for the negative i v(i) c 1 1 01 2 3 12 3 2 23 4 -7 3 5 4 34 6 -2 4 Vectorize your code c = sum(v>0) Example
  • 17. Comparing Elements v1=[1 3 2 7 4 -2] v2=[5 3 4 1 2 -2] for i=1:length(v1) if v1(i)>v2(i) v(i)=1; else v(i)=0; end end i v1(i) v2(i) v(i) 1 1 5 0 2 3 3 0 3 2 4 0 4 7 1 1 5 4 2 1 6 -2 -2 0 Vectorize your code: v= v1>v2 Example
  • 18. Vertical Motion % Vertical motion under gravity g = 9.81; % acceleration due to gravity u = 60; % initial velocity in metres/sec t = 0 : 0.1 : 12.3; % time in seconds s = u * t – g / 2 * t .ˆ 2; % vertical displacement in metres plot(t, s), title( ’Vertical motion under gravity’ ) xlabel( ’time’ ), ylabel( ’vertical displacement’ ) grid disp( [t’ s’] ) % display a table Example