NC Lab 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Numerical Analysis & Computation

EXPERIMENT 02

Introduction to Functions, Loops, Decision making and Plotting


of Various Signals in MATLAB.
Objectives:
• Familiarizing students with MATLAB programming
• Using of Functions, Loops and Decisions in MATLAB.

Software Tool:
• MATLAB installed on PCs
Background Knowledge:
MATLAB (short for MATrix LABoratory) is a platform (program) organized for optimized
engineering programming and scientific calculations. The MATLAB program implements
the MATLAB programming language and provides an extensive library of predefined
functions and make technical programming tasks easier and more efficient. MATLAB has
incredibly large variety of functions and toolkits with more functions and various
specialties
MATLAB is a very powerful and well-known software package that is used in science and
engineering disciplines, for numerical computation, data analysis, and graphical
visualization. It is available in almost all platforms such as personal computers, and
workstations running under several operating systems.
MATLAB contains a large collection of built-in functions and commands that are used in an
interactive mode, when you are in the command window. As soon as the name of a function
or a command is typed at the prompt in the command window, with the proper syntax, the
answer is displayed immediately. But there are two other windows, the edit window, and
graphics window, which will be discussed later.
The software package is designed to use additional sets of functions that are more
applicable disciplines such as control systems, digital signal processing, communications
engineering, and image processing. There are more than 20 sets known as “toolboxes” (e.g.,
control toolbox, digital signal processing toolbox, communication toolbox, and image
processing toolbox). All of them run under MATLAB and implement the functions based on
matrix manipulation of numerical data, and that is why the software is called MATLAB
(matrix laboratory).
MATLAB allows us to construct new functions using the enormous number of built-in
functions, commands, and operations in MATLAB and in the many toolboxes, without
having to know how to compile, link, load, and create executable code, because MATLAB
uses its own language to carry out all these steps, which are invisible to the user. It carries
out the steps and gives the answer very fast.

Department of Electrical Engineering, Air University Aerospace and Aviation Campus Kamra.
Compiled by: Engr M.Zain Ul Abideen
Numerical Analysis & Computation

MATLAB M files:
There are four ways of doing code in MATLAB. One can directly enter code in a
terminal window. This amounts to using MATLAB as a kind of calculator, and it is
good for simple, low-level work. The second method is to create a script M-file. Here,
one makes a file with the same code one would enter in a terminal window. When the file is
―run‖, the script is carried out. The third method is the function M-file. This method
actually creates a function, with inputs and outputs. The fourth method will not be
discussed here. It is a way to incorporate C code or FORTRAN code into MATLAB; this
method uses .mex. We will not discuss it here.

Script M files:
If we wish to execute repeatedly some set of commands, and possibly change input
parameters as well, then one should create a script M-file.
Such a file always has a ".m" extension, and consists of the same
commands one would use as input to a terminal.

Create a Script M-file:


To create a new script M-file, please follow the instructions on MATLAB interface.
Please note that these instructions are true for MATLAB R2011b. A new script file can
also be created by Ctrl+N command

File New Script


A new script file for MATLAB R2021a created by click on “New” and select “Script” Option.

Department of Electrical Engineering, Air University Aerospace and Aviation Campus Kamra.
Compiled by: Engr M.Zain Ul Abideen
Numerical Analysis & Computation

Now, save the script file as .m extension in selected folder(File name has no space, ‘_’ can
be used )

Write code in script/editor window and then run code by clicking on “Run” Option or
pressing “F5” button.

Department of Electrical Engineering, Air University Aerospace and Aviation Campus Kamra.
Compiled by: Engr M.Zain Ul Abideen
Numerical Analysis & Computation

Write the following code in Editor window and visualize the results.

Department of Electrical Engineering, Air University Aerospace and Aviation Campus Kamra.
Compiled by: Engr M.Zain Ul Abideen
Numerical Analysis & Computation
Cosine wave generation code in Editor window:

Write the following code in Editor window and visualize the results…..

Department of Electrical Engineering, Air University Aerospace and Aviation Campus Kamra.
Compiled by: Engr M.Zain Ul Abideen
Numerical Analysis & Computation
MATLAB code for area of a square and circle:

MATLAB code for area of a rectangle and triangle:

Department of Electrical Engineering, Air University Aerospace and Aviation Campus Kamra.
Compiled by: Engr M.Zain Ul Abideen
Numerical Analysis & Computation
Simple MATLAB code for multiplication of two matrices:

Function M-files:
Most of the M-files that one ultimately uses will be function M-files. These files again
have the ―.m‖ extension, but they are used in a different way than scripts. Function
files have input and output arguments, and behave like FORTRAN subroutines or C-
functions. In order to create a function M-file in MATLAB R2011b follow the
instructions

File New Function

To create a function M-file in MATLAB R2021a click on “New” and select “Function”.

Department of Electrical Engineering, Air University Aerospace and Aviation Campus Kamra.
Compiled by: Engr M.Zain Ul Abideen
Numerical Analysis & Computation
When you click on function option, the new window open as show below:

The structure of a typical function file, say my_fun.m, is as follows:

end

Note that the word function appears at the start of the file, and in lower case
letters. In addition, the outputs and inputs and name of the function are listed. Let
us return to the plot done in section 1.2.1. Suppose that instead of giving the vector
x, we want to make it a variable.
MATLAB code for area of a square using function:

Function

Department of Electrical Engineering, Air University Aerospace and Aviation Campus Kamra.
Compiled by: Engr M.Zain Ul Abideen
Numerical Analysis & Computation

Loops in MATLAB:
There are two prominent types of loop in MATLAB. These are:
i. for loop
ii. while loop
With loop control statements, you can repeatedly execute a block of code. Each loop starts
with the loop keyword such as “for” or “while” and end keyword is required to terminate
the respective loop.

(a) for Loop:


The "for" loop allows us to repeat certain commands. Basically, for statements loop a
specific number of times, and keep track of each iteration with an incrementing index

% for loop_index = [vector]

% code;

% end
EXAMPLES:

for i=[1:10] a=-5:5; a=1:10;


i; for j=1:length(a) sum_a=0;
end a(j) for j=1:length(a)
end sum_a=sum_a + a(j);
end
disp('sum of elements of a= ')
disp(sum_a)

Once MATLAB reads the "end" statement, it will loop through and print out ‘j’ each time.
For another example, if we define a vector and later want to change the entries, we can
change each individual entry using a for loop as used in the given example.

Department of Electrical Engineering, Air University Aerospace and Aviation Campus Kamra.
Compiled by: Engr M.Zain Ul Abideen
Numerical Analysis & Computation

In general the most common form of the for loop (for use in a program, not on the
command line) isfor index = j:k
Example

Product of two matrices using for loop code:


clc;
close all; clear all;
m=input('Enter No. of rows: ');
n=input('Enter No. of coulumns: ');

for i=1:m
for j=1:n
a(i,j)=input('values: ');
end
end
disp(a)
m1=input('enter rows: ');
n1=input('enter coulumns: ');
for k=1:m1
for t=1:n1
p(k,t)=input('values: ');
end
end
disp(p)
if n==m1
c=a*p;
fprintf('Product is:\n ')
disp(c)
else
disp('re-enter matrix')
end

Department of Electrical Engineering, Air University Aerospace and Aviation Campus Kamra.
Compiled by: Engr M.Zain Ul Abideen
Numerical Analysis & Computation

(b) while Loop:


while statements loop as long as a condition remains true. For example:

Length of a Vector:
The command length(A) is used to find the length of a vector A. For example:

To save this length in a variable, just assign this expression to a variable. For example:

Department of Electrical Engineering, Air University Aerospace and Aviation Campus Kamra.
Compiled by: Engr M.Zain Ul Abideen
Numerical Analysis & Computation

Size of a Matrix:
The command size() returns the size of a matrix in terms of number of rows and columns.

Nested Loops:
It is a good practice to indent the statements especially while using a nested loop. Nested
loops are often used in different programming problems. An example of a nested for loop
is given below:

Department of Electrical Engineering, Air University Aerospace and Aviation Campus Kamra.
Compiled by: Engr M.Zain Ul Abideen
Numerical Analysis & Computation

if Statements:
if statement evaluates an expression and executes a group of statements when the expression is
true. An expression is true when its result is non-empty and contains only non-zero elements.
Otherwise, the expression is false. The general form of the IF statement is:

if expression
statements
else if expression
statements
else
statements
end
The else and else if conditions are optional and depend on the type of functionality required
out of the code.

Use if, elseif, and else for Conditional Assignment:


The if, else if and else statements can be used for conditional assignment in a Matrix A. For
example:

Department of Electrical Engineering, Air University Aerospace and Aviation Campus Kamra.
Compiled by: Engr M.Zain Ul Abideen
Numerical Analysis & Computation

Test Arrays for Equality:


The if, else statements can be used to check whether 2 arrays are equal or not. For example:

If size(A) and size(B) are the same, concatenate the arrays; otherwise, display a
warning and return an empty array.
The result in the command window is:

Evaluate Multiple Conditions in Expression:


if, elseif, else
Execute statements if condition is true
Syntax
if expression
statements
elseif expression
statements
else
statements
end
if expression, statements, end evaluates an expression, and executes a group of statements
when the expression is true. An expression is true when its result is nonempty and contains
only nonzero elements (logical or real numeric). Otherwise, the expression is false.
The elseif and else blocks are optional. The statements execute only if previous expressions
in the if...end block are false. An if block can include multiple elseif blocks.

Department of Electrical Engineering, Air University Aerospace and Aviation Campus Kamra.
Compiled by: Engr M.Zain Ul Abideen
Numerical Analysis & Computation
The if else statements can also be used to evaluate multiple conditions in an expression.
For example, to determine if a value falls within a specified range:

The result in the command window is:

Elseif statement example code:


A simple code for student grading using if elseif statement and logical operators.

fprintf('Welcome\n')
math=input('Enter obtained marks in mathematics : ');
eng=input('Enter obtained marks in English : ');
physics=input('Enter obtained marks in Physics : ');
urdu=input('Enter obtained marks in urdu : ');
chem=input('Enter obtained marks in chemistry : ');
total_marks=500;
obtained_marks=math+eng+physics+urdu+chem
percentage=(obtained_marks/total_marks)*100
if(percentage>=90)
fprintf('Student Grade is A\n')
elseif(percentage>=80 && percentage<90 )
fprintf('Student Grade is B\n')
elseif(percentage>=70 && percentage<80 )
fprintf('Student Grade is C\n')
elseif(percentage>=60 && percentage<70 )
fprintf('Student Grade is D\n')
elseif(percentage>=50 && percentage<60 )
fprintf('Student Grade is E\n')
elseif(percentage>=40 && percentage<50 )
fprintf('Student Grade is F\n')
end

Department of Electrical Engineering, Air University Aerospace and Aviation Campus Kamra.
Compiled by: Engr M.Zain Ul Abideen
Numerical Analysis & Computation
When a code is run, it asks for a student marks in different subjects, calculate obtained
marks and then compute percentage of marks and display the Grade acquired by a student.

Department of Electrical Engineering, Air University Aerospace and Aviation Campus Kamra.
Compiled by: Engr M.Zain Ul Abideen
Numerical Analysis & Computation

Lab Tasks:
Question 1: Write a simple MATLAB code using function to calculate area of following?
 Circle
 Triangle
 Rectangle

Question 2: Write a simple MATLAB code in which dimension are taken from the user and
calculate area of a square, circle, rectangle and triangle?

Question 3: Write a simple MATLAB code in which row and column and entities are
entered by the user and simulate the result (Multiplication)?

Question 4: Write a simple MATLAB code for multiplication of two matrices using function?

Question 5:
a) Take an array matrix as input by user using input command and use Nested_for loop
statement to find whether this number is an Even number or an Odd number. Use display
command/fprintf to display “The entry is Even” or “The entry is Odd”, also count the
number of Even and Odd entries in a given matrix entered by user.
b) Take a positive integer as input using input command and use if-else statement to find
whether this number is a prime number or not. Use display command to display “This
number is prime” if the number is prime.

Question 6: Declare a vector A consisting of 9 elements. Use for loop to find the product of
all the elements of the vector and store the result in a variable 'z'. Subtract 12 from z and
store the final result in "c".

Question 7: Let “x” and “y” be two randomly generated row vectors. Create a new data
array “z”, based on the following set of rules:
a. If x = 0 and the value y lies within 52-336, then value of z will be 0. The value of z
will be 1 if y is less than 52 or more than 336.
b. If x = 1 and the value y lies within 38-176, then value of z will be 0. The value of z
will be 1 if y is less than 38 or more than 176.

Question 8: Use a while loop to print out the square of integers from 1 upto 20.

Question 9: Write MATLAB programs to find the following with for loops.

Department of Electrical Engineering, Air University Aerospace and Aviation Campus Kamra.
Compiled by: Engr M.Zain Ul Abideen

You might also like