0% found this document useful (0 votes)
24 views37 pages

Matlab - Basics-VSC-2024 02 01

The document provides an overview of MATLAB basics, covering arrays, variables, initialization, special values, arithmetic operations, and built-in functions. It includes examples of creating and manipulating arrays, performing arithmetic and relational operations, and using loops and functions. Additionally, it outlines exercises for practical application of the concepts discussed.

Uploaded by

b21102
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views37 pages

Matlab - Basics-VSC-2024 02 01

The document provides an overview of MATLAB basics, covering arrays, variables, initialization, special values, arithmetic operations, and built-in functions. It includes examples of creating and manipulating arrays, performing arithmetic and relational operations, and using loops and functions. Additionally, it outlines exercises for practical application of the concepts discussed.

Uploaded by

b21102
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

MATLAB Basics

Vishal Singh Chauhan


Arrays
The fundamental unit of data in MATLAB
Scalars are also treated as arrays by MATLAB (1 row and 1
column).
Row and column indices of an array start from 1.
Arrays can be classified as vectors and matrices.
Vector: Array with one dimension

Matrix: Array with more than one dimension

Size of an array is specified by the number of rows and the number


of columns, with the number of rows mentioned first (For example:
n x m array).
Total number of elements in an array is the product of the
number of rows and the number of columns.
Variables
• A region of memory containing an array, which is known by a
user-specified name.
• Contents can be used or modified at any time.
• Variable names must begin with a letter, followed by any
combination of letters, numbers and the underscore (_)
character. Only the first 31 characters are significant.
• The MATLAB language is Case Sensitive. NAME, name and
Name are all different variables.
Give meaningful (descriptive and easy-to-remember) names for
the variables. Never define a variable with the same name as a
MATLAB function or command.
Initializing Variables in Assignment Statements
An assignment statement has the general form
var = expression
Examples:
>> var = 40 * i; >> b = [1.0 2.0 3.0 4.0];
>> var2 = var / 5; >> c = [1.0; 2.0; 3.0];
>> array = [1 2 3 4]; >> d = [1, 2, 3; 4, 5, 6];
>> x = 1; y = 2; >> e = [1, 2, 3
>> a = [3.4]; 4, 5, 6];

‘;’ semicolon suppresses the automatic echoing of values but it


slows down the execution.
Examples (Contd.):

>> a2 = [0 1+8];
>> b2 = [a2(2) 7 a];
>> c2(2,3) = 5;
>> d2 = [1 2];
>> d2(4) = 4;
‘;’ semicolon suppresses the automatic echoing of values but it
slows down the execution.
Special Values
pi:  value up to 15 significant digits
Inf: infinity (such as division by 0)
NaN: Not-a-Number (division of zero by zero)
clock: current date and time in the form of a 6-element row
vector containing the year, month, day, hour, minute, and
second
date: current date as a string such as ‘22-Jan-24’
eps: epsilon is the smallest difference between two numbers
ans: stores the result of an expression
Special Values
• MATLAB includes a number of predefined special values.
These values can be used at any time without initializing
them.
• These predefined values are stored in ordinary variables.
They can be overwritten or modified by a user.
• If a new value is assigned to one of these variables, then that
new value will replace the default one in all later
calculations.
>> circ1 = 2 * pi * 10 % returns circ1 as 62.8319
>> pi = 3; % pi stored as 3
>> circ2 = 2 * pi * 10 % returns circ2 as 60
Never change the values of predefined variables.
Changing the data format
>> value = 12.345678901234567;
format short 12.3457
format long 12.34567890123457
format short e 1.2346e+001
format long e 1.234567890123457e+001
format short g 12.346
format long g 12.3456789012346
format rat 1000/81
Arithmetic operators Function Matlab syntax
+ Addition sin sin()
- Subtraction cos cos()
* Multiplication tan tan()
\ Left division sin-1 asin()
/ Right division cos-1 acos()
^ Exponentiation tan-1 atan()

By default angle will be considered


Function Matlab syntax to be in radians.
e exp()
ln log()
log10 log10()
 sqrt()
Exercises:
Arithmetic operations Trigonometry

Exponentials and logarithms

Obtain x = then verify 3x = 17


Exercises: Elementwise operations

The equation of a straight line is y = mx + c, where m and c are constants.


Compute the y-coordinates of a line with slope m = 0.5 and the intercept c = -2 at
the following x-coordinates:

x = 0, 1.5, 3, 4, 5, 7, 9, 10.

Create a vector t with 10 elements: 1 , 2, 3, . . . , 10. Now compute the


following quantities:
(i) x = t sin(t) (ii) y= (iii) z = sin(t2) / t2
Utility matrices
eye(m,n) m×n matrix with ones on the main diagonal
ones(m,n) m×n matrix of ones
zeros(m,n) m×n matrix of zeros
rand(m,n) m×n matrix of random numbers
randn(m,n) m×n matrix of normally distributed numbers
eye(m) m×m matrix with ones on the main diagonal
ones(m) m×m matrix of ones
zeros(m) m×m matrix of zeros
rand(m) m×m matrix of random numbers
diag(A) extracts diagonal of matrix A as a vector
diag(v) generates a diagonal matrix with vector v on diagonal
diag(A,1) extracts the first upper off-diagonal vector of matrix A
Create the following matrices using zeros, eye, ones
Creating vector
General command

v = initial value : increment : final value

Examples:

A = 0 : 10 : 100
B = 0 : pi/10 : 2*pi
C = 1 : 10 brackets not needed in these examples

However following needs brackets

D = [1:10 15:-1:10]
Built in functions to generate vectors
linspace(a,b,n) generates a linearly spaced vector of length n from a to b.

logspace(a,b,n) generates a logarithmically spaced vector of length n from


l0a to l0b
Relational operations

< less than


Generally the relational operators find
<= less than or equal to application in the conditional
> greater than statement (such as “if).
>= greater than or equal As such they compare two scalars or
to elements in two arrays.
== equal to
~= not equal to
Logical operations

& logical AND


| logical OR
~ logical complement (NOT)
>> A = [2 4 6;8 10 12]; B = [1 5 3;9 10 11];

>> A<B
>> A=1:3; B=[2;3];
ans =
0 1 0 >> A>=B
1 0 0
ans =
>> A>7 0 1 1
0 0 1
ans =
0 0 0
1 1 1

>> A>=B

ans =
1 0 1
0 1 1
Built in logical functions
all true (= 1) if all elements of a vector are true
any true (= 1) if any element of a vector is true
exist true (= 1 ) if the argument (a variable or a function) exists

isempty true (= 1) for an empty matrix


isfinite true for all finite elements of a matrix,
Subarrays
Make following arrays.
arr1 = [1.1 -2.2 3.3 -4.4 5.5 6.6 7.7 8.8];
Now use following and observe the result
arr1(3)
arr1([1 4])
arr1(1 : 2 : 8)

Now do the same exercise on the following matrix


arr2 = [1 2 3; -2 -3 -4; 3 4 5];
arr2(1, :)
arr2(:, 1:2:3)
Subarrays
The end function: When used in an array subscript, it returns the
highest value taken on by that subscript.
Make the following arrays
arr3 = [1 2 3 4 5 6 7 8]; arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12];
Now use the following command
arr3(5:end)
arr4(2:end, 2:end)
Using subarrays on the left hand-side of an assignment statement:
arr4(1:2, [1 4]) = [20 21; 22 23];
(1,1) (1,4) (2,1) and (2,4) are updated.
arr4 = [20 21; 22 23]; all of the array is changed.
Subarrays

Assigning a Scalar to a Subarray: A scalar value on the right-


hand side of an assignment statement is copied into every
element specified on the left-hand side.

>> arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12];


>> arr4(1:2, 1:2) = 1

arr4 =
1 1 3 4
1 1 7 8
9 10 11 12
Make following matrices using MATLAB commands

Now obtain following matrix using A, B, C


Symbols to manage features of a plot
Plot y = x/3, in the interval 0 to 10.

Plot y = sin(x) in the interval 0 to 2 . Select suitable number of points so that a smooth
curve is obtained. Put the x-label “angle in radians”, y-label “sin(x)”, and title “Sine wave
form”.

Plot the graph again changing the line style of graph to dashed.

Plot y = x2 – 5 x + 6 for x varying between 1 to 8. Keep the y-axis from -1 to 35.

Plot y1 = x and y2 = x - x3/6 + x5/240 in the same graph. Use 101 points within 0 to 2
including 0.

For the variation of x from 0 to 2 plot y1 = x; y2 = x - x3/6 + x5/240 and y3 = sin(x) in the
same graph with red, green and black coloured lines.

Plot any of the above graph with an x-axis (i.e. y = 0)


disp(X) displays array X without printing the array name

Displaying text on command prompt

disp(‘My Name’) displays “My Name” on the command


prompt.
Requesting user inputs
x = input(‘Enter the value of x’)
Displays “Enter the value of x” and waits for the user to input a
value and press return key. Value entered by user is assigned to
x.
For loop statement

for counter = start : increment : end

Statements about assignment to be done

end
For loop exercise:

1. Write a program to print numbers from 10 to 1. (Use for loop with


disp command).

2. Write a program that adds numbers from 1 to 50.


General form of while statement

while expression

Statements about assignment to be done

end
while loop exercise:

Use while loop to print numbers from 1 to 20.


Generalized forms of if statement

For single condition For multiple conditions

if expression if expression
statement
statement elseif expression
satement
end elseif expression
satement
end
if else exercise:

1. Write a program using if else statement to check whether a


number is within the rage from 5 to 25. Also display a message
“Number is within the range” or “Number is not within
permissible limits” as the case may be.

2. Write a program using if else statement to check whether a number


is less than zero, equal to zero or greater than zero. Also display a
suitable message.
Functions:
Syntax
function [y1,…,yN] = myfun(x1,...,xM)
Functions:
Syntax
function [y1,…,yN] = myfun(x1,...,xM)

Exercise on functions:
1. For a = [8 9 6 7 5] and b = [4 3 3 2 2] obtain matrices c, d & e such that
they are elementwise summation, multiplication and division respectively,
of the matrices a & b. Use a function to obtain answer.

2. Evaluate y = x3 for variation of x from 0 to 4 using a function. Then plot y


vs x.
Use function to solve the following:

3. Find the value of the polynomial y = 5x – 4x3 + 3 at x = 0, -1, 2. (Input


to the function is values of x and output is value of polynomial y)

4. Find the total amount and compound interest (CI)


on Rs.5000 for 2 years at a rate of 5% per annum compounded annually? [CI
= P (1 + r)n – P where P = Principal amount, r = rate of interest (annual), n =
no. of years. Thus input to the function will be P, r & n and the output will
be total amount A and compound interest CI)]
5. Write a function to obtain the factorial of a number. Input to
the function will be a number and output will be the factorial of that
number. (MATLAB has an inbuilt function “factorial”, you may
choose a different name for your function, and use inbuilt command
to verify result.)

You might also like