CAD Lect4 Matlab Arrays&Functions
CAD Lect4 Matlab Arrays&Functions
Lecture 4
Arrays in Matlab
Functions in Matlab
4
5
6
This function changes the dimensions of the array X to the new
size of MxN.
Syntax
7
8
Number of rows and columns of an array can be calculated using “size”
function.
Syntax >> [m,n]=size(X)
9
You can convert an array to a column vector using the colon (:) operator.
Note that the elements have been extracted from the array X, in a column-by-
column fashion.
10
Arrays can be concatenated (combined) together to produce larger arrays.
Note that here we have used the semicolon (;) to combine Z and X arrays
in the vertical direction.
11
Note that here we have used the comma (,) to combine X and R arrays in
the horizontal direction.
12
Two methods to access the elements within an array:
Row-and-column indexing.
Linear indexing.
13
>>a=X(1)
a=
3
>>b=X(7)
b=
8
>>c=X(12) >>c=X(end)
c= c=
10 10
14
You can use the colon operator (:) to access a Row in an array.
15
You can use the colon operator (:) to access a Column in an array.
16
To access the first and second rows of the third column.
To access the second, third, and fourth columns of the second row
To access the elements that are encircled by the rectangular area below:
17
To find the indices of the elements whose values is
greater than 7,
a= b=
This output means that the elements E(3,2) and E(1,3) are greater than 7.
To find the indices of the elements in the array E whose value is less than
3,
c= d=
To find the values of the elements in E that have values that are less than
3,
18
To find the elements in X whose values are greater than
3.
19
commands description
mean2 mean of matrix elements
std2 Standard deviation of matrix elements
det Matrix Determinant
inv Matrix inverse.
diag Matrix diagonal
trace Sum of diagonal elements
max(max(A)) Maximum element in matrix A
min(min(A)) Minimum element in matrix A
21
To improve the resolution of the 3D
plot, increase the number of points
within the X and Y arrays
22
The surf function plots an array as a surface
23
% y is 3x3x3 array
% a is 2x2x3 array
24
25
A Matlab function is a collection of commands that does a specific task
and must have a unique name.
Functions can improve Code Readability and Reusability.
Example:
Example:
27
The Matlab Editor pops up and write your function as :
Delete everything in the Editor and type the following code in the Editor
29
30
To call this function:
31
Many functions do not calculate values, but rather accomplish a task such as
printing formatted output.
Example
Call
since the function isn’t returning any value, it cannot be called from an
assignment statement:
32
A variable that is created within a function has a limited scope. This means
that this variable can be only accessed or modified by this function.
This variable is called a local variable.
Answer:
33
A variable created in the Command Window cannot be accessed by a
function.
Example:
35
36