You are on page 1of 16

Computer Programming

(CSC209)
Lecture (4)
Array Operation and Built-in
Functions
Dr.Anwar Hassan Ibrahim
Scalar Arrays Operation
Consist of two-dimensional matrices “layered” to
produce a third dimension. Each “layer” is called
a page

cat(n,A,B,C, ...) Creates a new array by


concatenating the
arrays A,B,C, and so
on along the
dimension n.

2
Array Addition and Subtraction
For example:
6 –2 + 9 8 = 15 6 (2.3-1)
10 3 –12 14 –2 17

Array subtraction is performed in a similar way.


The addition shown in equation 2.3–1 is performed in
MATLAB as follows:

>>A = [6,-2;10,3];
>>B = [9,8;-12,14]
>>A+B >> A-B
ans = ans =
15 6 -3 -10
-2 17 22 -11
Array Multiplication

2 9 6 27
3 5 =
–7 15 –21

This multiplication is performed in MATLAB as follows:

>>A = [2, 9; 5,-7];


>>3*A
ans =
6 27
15 -21

2-26
Multiplication of an array by a scalar is easily defined
and easily carried out.

However, multiplication of two arrays is not so


straightforward.

MATLAB uses two definitions of multiplication:

(1) array multiplication (also called element-by-element


multiplication), and

(2) matrix multiplication.

2-27
Matrix Operation

6
Array and Matrix Operations Example
a=
1 2
3 4
>> b = [-1 3; -1 2]
b=
-1 3
-1 2
>> c = a*b
c=
-3 7
-7 17

>> d = a.*b
d=
-1 6
7
-3 8
Try the following operation

8
Built-In Function in MATLAB
• Exponential
– exp(x) exp(25) = 7.2005e+10
– sqrt(x) sqrt(25) = 5
• Logarithmic
– log(x) natural logarithm ln log(10) = 2.3026
– log10(x) log10(10) = 1
– log2(x) log2(10) = 3.3219
• Maximum and Minimum
- max([x x1 …]) max ([1 -5 6 -3]) = 6
- min([x x1 …]) min ([1 -5 6 -3]) = -5
[maxval, index] = max ([1 -5 6 -3])= 6 and 3
Built-In Function in MATLAB
• numeric
– ceil(x) round to nearest integer towards +
– fix(x) round to nearest integer towards 0
– floor(x) round to nearest integer towards -
– round(x) round to nearest integer
– sign(x) +1, 0 or -1
– rem(x,y) Finds remainder of x/y
• complex
– abs(x) absolute value
– angle(x) in complex plane
– conj(x) Complex Conjugate
– imag(x)
– real(x)
Built-In Function in MATLAB
• Trigonometric and their inverse
– cos(x) acos(x)
– sin(x) asin(x)
– tan(x) atan(x)
– cot(x) acot(x)
– csc(x) acsc(x)
– sec(x) asec(x)
Built-In Function in MATLAB
• Hyperbolic and their inverse
– cosh(x) acosh(x)
– coth(x) acoth(x)
– csch(x) acsch(x)
– sech(x) asech(x)
– sinh(x) asinh(x)
– tanh(x) atanh(x)
Built-In MATLAB Functions
Using MATLAB Functions with Array Inputs
For example, if
x = [0 : pi/2*pi 3*pi/2 : 2*pi],
y = sin(x)
y = [0 0.8415 0.9093 0.1411 -0.7568 -1.0000 -0.5403].

Common MATLAB Functions


>> sqrt(-2)
ans =
0.0000 + 1.4142i
>> sqrt(2)
ans =
13
1.4142
Built-In MATLAB Functions
Examples
Compute the equation below using Matlab
(1) y = e −a sin(x) + 10√y , for a = 5, x = 2, and y = 8

(2) (3)

14
Practice & Quiz 3

15
END & Assignment

16

You might also like