Programming Languages MatLab(Lec1-4)_removed
Programming Languages MatLab(Lec1-4)_removed
Overview
Basic Syntax
Commonly used Operators and Special Characters
Special Variables and Constants
Saving Your Work
Naming Variables
Long Assignments
The format Command
Basic Syntax
MATLAB environment behaves like a super-complex calculator. You can
enter commands at the >> command prompt.
MATLAB is an interpreted environment. In other words, you give a command
and MATLAB executes it right away.
Type a valid expression, for example,
>>5 + 5 And press ENTER
When you click the Execute button, or type Ctrl+E, MATLAB executes it
immediately and the result returned is:
• ans = 10
Let us take up few more examples:
>>3 ^ 2 % 3 raised to the power of 2
ans = 9
• Another example,
>>sin(pi /2) % sine of angle 90
ans = 1
Use of Semicolon (;) in MATLAB
•Semicolon (;) indicates end of statement. However, if you want to suppress and hide
the MATLAB output for an expression, add a semicolon after the expression.
For example,
>>x = 3;
>>y = x + 5
The output:
y=8
Adding Comments
• The percent symbol (%) is used for indicating a comment line. For example,
>>x = 9 % assign the value 9 to x
Commonly used Operators and Special Characters
• MATLAB supports the following commonly used operators and special
characters:
Operator Purpose
+ Plus; addition operator.
- Minus; subtraction operator.
* Scalar and matrix multiplication operator.
.* Array multiplication operator
^ Scalar and matrix exponentiation operator.
.^ Array exponentiation operator.
\ Left-division operator.
/ Right-division operator.
.\ Array left-division operator.
./ Array right-division operator.
: Colon; generates regularly spaced elements and
represents an entire row or column.
. Decimal point.
24
Commonly used Operators and Special Characters
• MATLAB supports the following commonly used operators and special
characters:
Operator Purpose
25
Special Variables and Constants
Name Meaning
Inf Infinity.
pi The number π
26
Saving Your Work
The save command is used for saving all the variables in the
workspace, as a file with .mat extension, in the current
directory.
For example,
>>save myfile
You can reload the file anytime later using the load
command.
>>load myfile
27
Naming Variables
Variable names consist of a letter followed by any
number of letters, digits or underscore.
28
Naming Variables
The who command displays all the variable names you
have used.
>>who
Your variables are:
a ans b c x y
The whos command displays little more about the variables:
Variables currently in memory Type of each variables
Memory allocated to each variable Whether they are
complex variables or not
29
Commands for Managing a Session
Command Purpose
30
The format Command
• By default, MATLAB displays numbers with four decimal place
values. This is known as short format.
• However, if you want more precision, you need to use the format
command. The format long command displays 16 digits after
decimal.
>>format long
>>x = 7 + 10/3 + 5 ^ 1.2
The output
x=
17.231981640639408
• The format bank command rounds numbers to two decimal
places. For example,
>>format bank
>>weekly_wage = 177.45 * 6
• The output : weekly_wage =
1064.70
Lecture 3:
Overview
M-file
Trigonometry Function
Arithmetic Operations
The M Files
MATLAB allows writing two kinds of program files:
• Scripts - script files are program files with .m extension. In these
files, you write series of commands, which you want to execute
together. Scripts do not accept inputs and do not return any outputs.
They operate on data in the workspace.
• Functions - functions files are also program files with .m extension.
Functions can accept inputs and return outputs. Internal variables
are local to the function.
You can use the MATLAB editor or any other text editor to create your .m files.
In this section, we will discuss the script files. A script file contains multiple
sequential lines of MATLAB commands and function calls. You can run a
script by typing its name at the command line.
After creating and saving the file, you can run it in two ways:
Clicking the Run button on the editor window or Just typing the
filename (without extension) in the command prompt
33
Trigonometry
The trigonometric functions in MATLAB calculate standard trigonometric values in radians
or degrees, hyperbolic trigonometric values in radians, and inverse variants of each
function.
Function work
Sin (x) Sine of argument in radians
Sind (x) Sine of argument in degrees
asin (x) Inverse sine in radians
asind (x) Inverse sine in degrees
sinh (x) Hyperbolic sine
asinh (x) Inverse hyperbolic sine
cos (x) Cosine of argument in radians
cosd (x) Cosine of argument in degrees
acos (x) Inverse cosine in radians
acosd (x) Inverse cosine in degrees
cosh(x) Hyperbolic cosine
acosh(x) Inverse hyperbolic cosine
tan(x) Tangent of argument in radians
tand(x) Tangent of argument in degrees
atan(x) Inverse tangent in radians
atand(x) Inverse tangent in degrees
tanh(x) Hyperbolic tangent
atanh(x) Inverse hyperbolic tangent
34
Trigonometry
Function work
csc (x) Cosecant of input angle in radians
cscd(x) Cosecant of argument in degrees
acsc(x) Inverse cosecant in radians
acscd(x) Inverse cosecant in degrees
csch(x) Hyperbolic cosecant
acsch(x) Inverse hyperbolic cosecant
sec (x) Secant of angle in radians
secd(x) Secant of argument in degrees
asec(x) Inverse secant in radians
asecd(x) Inverse secant in degrees
sech(x) Hyperbolic secant
asech(x) Inverse hyperbolic secant
deg2rad(x) Convert angle from degrees to radians
rad2deg(x) Convert angle from radians to degrees
H.W: How to convert between angle degree and radians solve with example?
35
Arithmetic Operations
Arithmetic functions include operators for simple operations like addition and
multiplication, as well as functions for common calculations like summation,
moving sums, modulo operations, and rounding.
Function work
mod Remainder after division (modulo operation)
rem Remainder after division
ceil Round toward positive infinity
fix Round toward zero
floor Round toward negative infinity
round Round to nearest decimal or integer
mod Syntax
b = mod(a,m)
Description
b = mod(a,m) returns the remainder after division of a by m, where a is the
dividend and m is the divisor. This function is often called the modulo
operation, which can be expressed as b = a - m.*floor(a./m). The mod
function follows the convention that mod(a,0) returns a.
Example: >>mod(23,5)
ans= 3 36
>>a = [-4 -1 7 9]; m = 3;
>>b = mod(a,m)
The output:
b=
2 2 1 0
• rem Syntax
r = rem(a,b)
Description
r = rem(a,b) returns the remainder after division of a by b, where a is the dividend and b is the
divisor. This function is often called the remainder operation, which can be expressed as r = a
- b.*fix(a./b). The rem function follows the convention that rem(a,0) is NaN.
>>a = [-4 -1 7 9]; b = 3;
>>r = rem(a,b)
The output:
r=
-1 -1 1 0
>>a = 23; b = 5; r = rem(a,b)
The output:
r=
3
Ceil Syntax
Y = ceil(X)
Y = ceil(t)
Description
• Y = ceil(X) rounds each element of X to the nearest integer greater than or equal
to that element.
>> x = 4.3;
>>y = ceil(x);
The output:
y=5
another example:
>> ceil(-4.9)
The output:
ans =
-4
• Y = ceil(t) rounds each element of the duration array t to the nearest number of
seconds greater than or equal to that element.
>>A = [1.3, 6.8, 5.1, 9.9, 2.2];
>> B = ceil(A);
The output:
B=
2 7 6 10 3
fix Syntax
Y = fix(X)
Description
Y = fix(X) rounds each element of X to the nearest integer toward zero. This
operation effectively truncates the numbers in X to integers by removing the decimal
portion of each number:
• For positive numbers, the behavior of fix is the same as floor.
• For negative numbers, the behavior of fix is the same as ceil.
>> X = [-1.9 -3.4; 1.6 2.5; -4.5 4.5];
>> Y = fix(X)
The output:
Y=
-1 -3
1 2
-4 4
floor Syntax
Y = floor(X)
Y = floor(t)
Description
• Y = floor(X) rounds each element of X to the nearest integer less than or equal to that element.
>> floor(8.9)
The output:
ans =
8
• Y = floor(t) rounds each element of the duration array t to the nearest number of seconds less than or
equal to that element.
>> A = [1.3, 6.8, 5.1, 9.9, 2.2];
>> B = floor(A)
The output:
B=
1 6 5 9 2
>> A = [-4.1, -8.8, -3.9];
>> B = floor(A)
The output:
B=
-5 -9 -4
round Syntax
Syntax
Y = round(X)
Y = round(X,N)
Description
• Y = round(X) rounds each element of X to the nearest integer. In the case of a tie, where an element
has a fractional part of 0.5 (within roundoff error) in decimal, the round function rounds away from
zero to the nearest integer with larger magnitude
>> round(6.78)
The output:
ans =
7
Y = round(X,N) rounds to N digits:
• N > 0: round to N digits to the right of the decimal point.
• N = 0: round to the nearest integer.
• N < 0: round to N digits to the left of the decimal point.
>>round(863178137,-2)
The output:
ans =
863178100
>>Y = round(pi,3)
The output: Y =
3.1420
• sqrt
Square root
Syntax
B = sqrt(X)
Description
B = sqrt(X) returns the square root of each element of the array X.
>> X = 16;Y = sqrt(X)
Y=
4
• log10
Common logarithm (base 10)
Syntax
Y = log10(X)
Description
Y = log10(X) returns the common logarithm of each element in array X. The function accepts both real
and complex inputs. For real values of X in the interval (0, Inf), log10 returns real values in the interval (-
Inf ,Inf).
>>log10(1)
ans =
0
>>log10(100)
ans =
2
• log2 Syntax
Y = log2(X)
Description
Y = log2(X) computes the base 2 logarithm of the elements of X such that 2𝑦 = 𝑋
>>X = 8;
>>Y = log2(X)
The output:
ans =
• exp function
Exponential
Syntax
Y = exp(X)
Description
Y = exp(X) returns the exponential ex for each element in array X.
>>exp(1)
The output:
ans =
2.7183
• log
Natural logarithm (Ln: Ln is called the natural logarithm. It is also called the logarithm of the base e)
Syntax
Y = log(X)
Description
Y = log(X) returns the natural logarithm ln(x) of each element in array X.
The natural logarithm follows the same rules as the common logarithm
(logarithm with base 10, usually written as log). That is, ln (ab) = ln a + ln b;
ln (a/b) = ln a – ln b; and ln (ab) = b ln a. The natural logarithm and the
common logarithm are related through
log 𝑥
ln 𝑥 =
log 𝑒
l𝑛 𝑥
log 𝑥 =
l𝑛 10
>> log(5)
ans =
1.6094
• gcd
Greatest common divisor.
syntax
G = gcd(A,B)
Description
G = gcd(A,B) is the greatest common divisor of corresponding elements of A and B. The arrays
A and B must contain integer values and must be the same size (or either can be scalar).
gcd(0,0) is 0 by convention; all other GCDs are positive integers.
>>gcd(4,8)
The output:
ans=
2
>> a=[4 5 8];b=[6,8,12];
>>gcd(a,b)
The output:
ans =
2 1 4
Lecture 4:
Overview
1D array
linspace function
logspace function
1D array(Vectors)
A vector is an ordered list of numbers. You can enter a vector of any length in MATLAB by typing a list of
numbers, separated by commas or spaces, inside square brackets. For example,
>> Z = [2,4,6,8]
Z=
2468
>> Y = [4 -3 5 -2 8 1]
Y=
4 -3 5 -2 8 1
Suppose you want to create a vector of values running from 1 to 9. Here’s how to do it without typing each number:
>> X = 1:9
X=
123456789
>> X = 0:2:10
X=
0 2 4 6 8 10
• You can also use fractional or negative increments, for example, 0:0.1:1 or 100:-1:0.
The elements of the vector X can be extracted as X(1), X(2), etc. For example,
>> X(3)
ans =
4
To change the vector X from a row vector to a column vector, put a prime (’) after X:
>> X’
ans =
0
2
4
6
8
10
You can perform mathematical operations on vectors. For example, to square the elements of the vector X, type
The following table shows various commands used for working with arrays,
matrices and vectors:
Command purpose
length Computes number of elements.
max Returns largest element.
min Returns smallest element.
prod Product of each column.
reshape Changes size.
sort Sorts each column, element.
sum Sums each column.
linspace Creates regularly spaced vector.
logspace Creates logarithmically spaced vector.
length
Length of largest array dimension
Syntax
L = length(X)
Description
L = length(X) returns the length of the largest array dimension in X. For vectors, the length is simply the
number of elements. For arrays with more dimensions, the length is max(size(X)). The length of an empty
array is zero.
>>v = 5:10
v=
5 6 7 8 9 10
>>L = length(v)
L=
• max
Largest elements in array
Syntax
M = max(A)
>> a=[1,3,5,6,3];max(a)
ans =
6
• min
Smallest elements in array
Syntax
M = min(A)
>> a=[1,3,5,6,3];min(a)
ans =
1
• prod
Product of array elements
Syntax
B = prod(A)
Description
B = prod(A) returns the product of the array elements of A.
Example:
>> A =[1 2 3 4]
A=
1234
>> prod(A)
ans =
24
logspace
sum Generate logarithmically spaced vector
Sum of array elements Syntax
Syntax • y = logspace(a,b)
• y = logspace(a,b,n)
S = sum(A) Description
Description y = logspace(a,b) generates a row
S = sum(A) returns the sum of vector y of 50 logarithmically spaced
the elements of A along the first points between decades 10^a and
array dimension whose size does 10^b. The logspace function is
especially useful for creating
not equal 1.
frequency vectors. The function is
>>A = 1:10; the logarithmic equivalent of
>>S = sum(A) linspace and the ‘:' operator.
S= y = logspace(a,b,n) generates n
points between decades 10^a and
55 10^b.
linspace
Generate linearly spaced y = linspace(x1,x2,n)
vector generates n points. The
Syntax spacing between the points
• y = linspace(x1,x2) is (x2-x1)/(n-1).
•y = linspace(x1,x2,n)
>>y1 = linspace(-5,5,7)
Description
y = linspace(x1,x2) returns a y1 =
row vector of 100 evenly
spaced points between x1 and -5.0000 -3.3333 -1.6667
x2. 0 1.6667 3.3333 5.0000
المصادر
• https://www.mathworks.com/help/matlab/index.html?s_tid=CRUX_lftnav
51