You are on page 1of 166

Computer Programming (MATLAB)

Dr. Samir Kale


Revision Class-01/03/2019
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
BITS Pilani
Hyderabad Campus

MID SEM Revision-Lecture 1


Outcomes for the course

1. Students will be able to understand the MATLAB applications in


numeric computation and algorithm development
2. Students will be able to write MATLAB code for application in Control
Systems, Statistics Finite Element Method
3. Students will be able to write MATLAB script to understand the
response of a process with respect to the given input
Textbook and Reference Book
T1 Stephen J. Chapman Matlab Programming for Engineers, 4th Ed. Cengage
Learning.
T2 Stormy Attaway Matlab: A Practical Introduction to Programming and
Problem Solving
R1 Amos Gilat MATLAB An Introduction with Applications, 5th Edition Wiley
Publications
TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus
BASICS OF MATLAB

1st Contact Hour : 02.00-4.00

Scalars Arrays Functions


MATLAB MATLAB
and and
Features Desktop
Matrices Programs

TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


MATLAB Free Version Installation

1. https://in.mathworks.com/products/matlab.html

2. https://in.mathworks.com/campaigns/products/trials.html?prodcode=ML

3. Put your Email and Download the trial license, use BITS email only

4. Ensure you choose 64 bit

5. Download on the system and Start working

TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


MATLAB Features and Significance

1. Ease of use, Platform Independence, Predefined functions, GUI, Plotting,


MATLAB Compiler

2. Applied Fields:

– Comprises of Mathematical Functions


– Ability to solve Differential Equations
– Ability for better interface with other software
– Gaussian Waves
– Wavelet Analysis
– Statistics
– Earth sciences & Neurosciences
– Modeling and Simulation
– And Many More

TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


MATLAB Desktop

TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


1. MATLAB-Basic Syntax

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.

8 TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


MATLAB-Basic Syntax

Operator Purpose

./ Array right-division operator.

: Colon; generates regularly spaced elements and represents an entire row or column.

() Parentheses; encloses function arguments and array indices; overrides precedence.

[] Brackets; enclosures array elements.

. Decimal point.

… Ellipsis; line-continuation operator

, Comma; separates statements and elements in a row

; Semicolon; separates columns and suppresses display.

% Percent sign; designates a comment and specifies formatting.

= Assignment operator.

9 BITS Pilani, Deemed to be University under Section 3, UGC Act


2. MATLAB-Hierachy of Operations

In MATLAB, and many other programming languages, operations are performed in the
following order:

• expressions in brackets: ( ) ;

• powers: ^ ;

• multiplication and division: * , / ;

• addition and subtraction: + , - .

• Operations of the same precedence, for example multiplication and division,


are evaluated from left to right.

In ordinary written mathematics we sometimes leave out brackets and rely on the fact that an
intelligent human will understand where they ought to go. In contrast, computers obey
exactly the rules for evaluating expressions. If you are unsure, adding some extra brackets
(parentheses) will not hurt

10 BITS Pilani, Deemed to be University under Section 3, UGC Act


2. MATLAB-Arithmatic Expressions
MATLAB Window Result

>> 5+6 ans=11 { ans is default variable name}

>> a=5 c=11


>> b=6
>>c=a+b Or >>plus(a,b)

>> 1+2*3 ans =7

>>(1+2)*3 >>? solve

>> 4/2+1 >> ans=3

>> 1+4/2 >> ? solve

>> 8^2/3 >> ans=21.33

>> 8^(2/3)

>> 12/2/3 >> ? Solve

>> 12/(2*3) >> 2

>> 4^3^2 >> ans=4096

>> 4^(3^2) >> ans=262144


11 BITS Pilani, Deemed to be University under Section 3, UGC Act
3. MATLAB-Variables
Variable names are an example of identifier names. We will see other examples

The name must begin with a letter of the alphabet. After that, the name can contain
letters, digits, and the underscore character (e.g., value_1), but it cannot have a space.

There is a limit to the length of the name; the built-in function Name length max tells how many
characters this is.

MATLAB is case-sensitive. That means that there is a difference Between upper- and lowercase
letters. So, variables called mynum , MYNUM, and Mynum are all different.

There are certain words called reserved words that cannot be used as variable
names. Names of built-in functions can, but should not, be used as variable names.

pi =3.14159….
i= 1
j= 1
inf =infinity ∞
NaN= stands for “not a number”; e.g., the result of
0/0
12 BITS Pilani, Deemed to be University under Section 3, UGC Act
3. MATLAB-Commands

>> whos
>>clc
>> doc
>> rand
>>disp
>>input
>>fprintf
Sample Script

% This script calculates the area of a circle


% It prompts the user for the radius
% Prompt the user for the radius and calculate
% the area based on that radius
radius = input(‘Please enter the radius: ’);
area = pi * (radius^2);
% Print all variables in a sentence format
fprintf(‘For a circle with a radius of %.2f,’,radius)
fprintf(‘the area is %.2f\n’,area)

13 BITS Pilani, Deemed to be University under Section 3, UGC Act


3. MATLAB-First Program

#include <stdio.h>
int main()

{
double n1, n2, n3;

printf("Enter three numbers: ");


scanf("%lf %lf %lf", &n1, &n2, &n3);

if( n1>=n2 && n1>=n3 )


printf("%.2f is the largest number.", n1);
MATLAB CODE
if( n2>=n1 && n2>=n3 )
printf("%.2f is the largest number.", n2);
a = 20;
If( n3>=n1 && n3>=n2 ) b = 10;
printf("%.2f is the largest number.", n3); return 0; c = 30;

data = [a,b,c];
}
largest = data(1);

for i = 1:length(data) I

f data(i) > largest;

largest = data(i);
end
end

14 BITS Pilani, Deemed to be University under Section 3, UGC Act


MATLAB-First Program

Physicists tell us that altitude h in feet of a projectile t seconds after firing is

h= -16t2 +vot +h0

where vo is the initial velocity in ft/s and ho is altitude in from which it is fired. If a

rocket is launched from a hilltop 2400 ft above the desert with an initial upward

velocity of 400 ft/s, then when will it land on the desert

15 BITS Pilani, Deemed to be University under Section 3, UGC Act


Practice Problems and Examples-
Homework

16 BITS Pilani, Deemed to be University under Section 3, UGC Act


Practice Problems and Examples-
Homework

2) Change the Current directory to mynewdir. Then open an Edit Window and add the
following lines

% Create an input array from -2*pi to 2*pi

t=-2*pi:pi/10:2*pi
% Calculate |sin(t)|
x=abs(sin(t));
% Plot result
plot(t,x)

17 BITS Pilani, Deemed to be University under Section 3, UGC Act


Practice Problems and Examples-
Homework

3) Think about what the results would be for the following expressions, and then type
them to verify your answers.

• 25 / 4 * 4
• 3+4^2
• 4 \ 12 + 4
• 3 ^ 2 (5 – 2) * 3

4) Using the colon operator, create the following vectors

• 3456
• 1.0000 1.5000 2.0000 2.5000 3.0000
• 5432

18 BITS Pilani, Deemed to be University under Section 3, UGC Act


Vectors and Matrices

Vectors and matrices are used to store sets of values, all of which are the same
type. A vector can be either a row vector or a column vector. A matrix can be
visualized as a table of values. The dimensions of a matrix are r × c, where r is
the number of rows and c is the number of columns. This is pronounced “r by c.”
If a vector has n elements, a row vector would have the dimensions 1 × n, and a
column vector would have the dimensions n × 1. A scalar (one value) has the
dimensions 1 × 1. Therefore, vectors and scalars are actually just subsets of
matrices. Here are some diagrams showing, from left to right, a scalar, a column
vector, a row vector, and a matrix:

19 BITS Pilani, Deemed to be University under Section 3, UGC Act


Vectors and Matrices

A particular element in a vector is accessed using the name of the vector variable
and the element number (or index, or subscript) in parentheses. In MATLAB,
the indices start at 1. Normally, diagrams of vectors and matrices show the
indices; for example, for the variable newvec created earlier the indices 1–10

20 BITS Pilani, Deemed to be University under Section 3, UGC Act


BITS Pilani
Hyderabad Campus

MID SEM Revision-Lecture 2


Commands

Commands Usage
clc Clear command window
pwd Working directory
ans =
'C:\Users\hp\Documents\MATLAB‘
s=pwd
mkdir Making a directory
directory listing Dir
cd Change the working directory
delete Delete the files
diary filename Saves the subsequent commands in a file

TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


Commands

Commands Usage
who Variable name
whos Variable names, sizes, number of bytes
what Files available in workspace
which Which mean
clear clear all variables, clear all-Global variables also
save save data4 x y z
Save –append Save data4 x1 y1 z1
Save –ascii Save text.txt x y –ascii
Load Load filename
Type Type average % will type contents in a file

TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


Commands

Precedence Usage
() 1
^ 2
- 3
abs(x) Aabsolute value of x *,/, \ 4
Angle(x) Phase angle of complex number x +, / 5
Ceil(x) Smallest integer greater than real number x
Conj(x) Conjugate of a number
Exp(x) Exponential value
Factorial (x) Factorial of a number
Fix(x) Rounds a real number towards zero fix(2.3)=2
Floor(x) Floor(2.36) will give 2
Rem(x,y) Remainder, rem(10.5,-2.7)=2.4
Round(x) Round(2.36)--2
TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus
Commands

abs(x) Aabsolute value of x


Sign(x) Signum function 1 or -1
Sqrt(x) Square root of a number
Log(x) Natural logarithm of a number
Log10(x) Logarithm of x to the base 10
mod(x,y) Gives remainder

TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


Arrays Basics

• Matrices can be of different sizes, either square matrices of size NxN or rectangular NxM

• Note that vectors are special case of matrices.

TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


Matrix Operation

Practicals MATLAB Window


This is how you can enter a row vector
Create a 3*2 matrix a >> a=[1 2 3 4 5]

Create a row vector 1*4 a=

Create 3*1 array 1 2 3 4 5

Row 1 4 5 6 7

Row 2 8 9 10 11

12 13 14 15
Row 3
16 17 18 19
Row 4
>> b=[1;2;3;4]

b=

Column 1 Column 2 Column 3 Column 4 1


2
3
4

TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


Matrix Operations-some commands

This is how you can enter ones command ones(1,5)

ans =

1 1 1 1 1
This is how you can enter a zeros vector zeros(3,2)

ans =

0 0
0 0
This is how you can enter an identity matrix 0 0

eye(2,2)
ans =
1 0
0 1

TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


Matrix Operations-Addition, Multiplication and Inverse

>> a=zeros(2,2)
a=
Step 1
0 0
0 0

>> b=eye(2,2)
b= Step 2

1 0
0 1
>> c=a+b Step 3
c=

1 0
0 1

TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


Matrix Operations-Initializing with shortcut Expressions

Colon Operator

First:incr:last

>> x=1:2:10

Initializing with built in functions


a=zeros(2);
B=zeros(2,3)
C=[1,2;3,4]
D=zeros(size(c));

Other built in functions


ones
eye
length
size

TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


Matrix Operations-Addition, Multiplication and Inverse

>> a=[1 2;3


4] Step 1
a=

1 2
3 4 Step 2
Multiplication
>> b=[2 3; 4
5]
b=

2 3 Step 3
4 5

>> a*b

ans =

10 13
22 29
31

TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


Multi Dimensional Arrays

Row 1 >> c(:,:,1)=[1,2,3;4,5,6] 1


>>c(:,:,2)=[7,8,9;10,11,12] a(1,1)
Row 2 4
a(2,1)
Row 3 7
a(3,1)
Row 4 10
a(4,1)
2
a(1,2)
Col 1 5
Col 2 a(2,2)
Col 3 8
Col 4 Col5 a(3,2)
11
Row 1
a(4,2)
3
a(1,3)
Row 2 6
Row 3
a(2,3)
9
a(3,3)
Row 4 12
a(4,3)

TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


Sub Arrays

arr1=[1.1 -2.2 3.3 -4.4 5.5]


A = [23 42 37 18 52];

M = max(A) Create a vector and compute its largest


arr1(3) =? element.
M = 52
arr1([1 4]) =?

arr1(1:2:5)=?

end function
arr3=[1 2 3 4 5 6 7 8]
arr3(5:end)=? A = [-2+2i 4+i -1-3i]; Create a complex vector and compute its
largest element, that is, the element with the
arr4=[1,2,3,4;5,6,7,8;9,10,11,12] max(A) largest magnitude.

ans = 4.0000 + 1.0000i


arr4(2:end,2:end)

TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


Matrix Operations-Maximum and Minimum values

• Create a matrix and compute the largest element in each


row.
• A = [1.7 1.2 1.5; 1.3 1.6 1.99]

• A = 1.7000 1.2000 1.5000


• 1.3000 1.6000 1.9900

• M = max(A,[ ],2)

• M = 1.7000 1.9900

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


• Sub Arrays_Practice

arr4=[1,2,3,4;5,6,7,8;9,10,11,12]  for loops


 If loop
arr4(1:2,[1 4])=[20 21; 22 23]  Switch case
 Plot commands
Quiz  Symbolic Mathematics
 File handling
c=[1.1 -3.2 3.4 0.6; 0.6 1.1 -0.6 3.1;1.3,0.6,5.5,0.0]

(a) c(2,:)
(b) c(1:2,2:end)
(c) c([2 2],[3 3])
(d) c([1 3],2)
(e) c(4:end)

35

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


M AT L A B - F i r s t P r o g r a m

a = 20;
b = 10;
c = 30;

data = [a,b,c];

largest = data(1);

for i = 1:length(data)

if data(i) > largest;

largest = data(i);

end
end
MATLAB-First Program

#include <stdio.h>
int main()

{
double n1, n2, n3;

printf("Enter three numbers: ");


scanf("%lf %lf %lf", &n1, &n2, &n3);

if( n1>=n2 && n1>=n3 )


printf("%.2f is the largest number.", n1);
MATLAB CODE
if( n2>=n1 && n2>=n3 )
printf("%.2f is the largest number.", n2);
a = 20;
If( n3>=n1 && n3>=n2 ) b = 10;
printf("%.2f is the largest number.", n3); return 0; c = 30;

data = [a,b,c];
}
largest = data(1);

for i = 1:length(data) I

f data(i) > largest;

largest = data(i);
end
end

37 BITS Pilani, Deemed to be University under Section 3, UGC Act


MATLAB Free Version Installation

1. https://in.mathworks.com/products/matlab.html

2. https://in.mathworks.com/campaigns/products/trials.html?prodcode=ML

3. Put your Email and Download the trial license, use BITS email only

4. Ensure you choose 64 bit

5. Download on the system and Start working

TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


MATLAB-First Program

Physicists tell us that altitude h in feet of a projectile t seconds after firing is

h= -16t2 +vot +h0

where vo is the initial velocity in ft/s and ho is altitude in from which it is fired. If a

rocket is launched from a hilltop 2400 ft above the desert with an initial upward

velocity of 400 ft/s, then when will it land on the desert

39 BITS Pilani, Deemed to be University under Section 3, UGC Act


Practice Problems and Examples-
Homework

3) Think about what the results would be for the following expressions, and then type
them to verify your answers.

• 25 / 4 * 4
• 3+4^2
• 4 \ 12 + 4
• 3 ^ 2 (5 – 2) * 3

4) Using the colon operator, create the following vectors

• 3456
• 1.0000 1.5000 2.0000 2.5000 3.0000
• 5432

40 BITS Pilani, Deemed to be University under Section 3, UGC Act


Applications –Lecture 2

A sphere has a radius of 24 cm. A rectangular prism has sides of a, a/2, and a/4
.
(a) Determine a of a prism that has the same volume as the sphere.
(b) Determine a of a prism that has the same surface area as the sphere

Solution in MATLAB

clear, clc
r=24;
disp('Part (a)')
%need to solve (a)(a/2)(a/4)=4/3 pi r^3
%could also use ^(1/3)
a=nthroot(8*4/3*pi*r^3,3)
disp('Part (b)')
%need to solve 2(a^2/2+a^2/4+a^2/8)=4 pi r^2
a=sqrt(8/7*4*pi*r^2)
disp(' ')

41 BITS Pilani, Deemed to be University under Section 3, UGC Act


Applications –Lecture 2

The voltage difference V between points a and b in the Wheatstone bridge circuit is:

Calculate the voltage difference when V = 14 volts, R1 = 120.6 ohms, R2 = 119.3 ohms, R3 =
121.2 ohms, and R4 = 118.8 ohms.

42 BITS Pilani, Deemed to be University under Section 3, UGC Act


Applications –Lecture 2

clear,
clc
V=14; R1=120.6; R2=119.3; R3=121.2; R4=118.8;
Vab=V*(R1*R3-R2*R4)/((R1+R3)*(R3+R4))

43 BITS Pilani, Deemed to be University under Section 3, UGC Act


Applications –Lecture 2

The number of combinations Cn,r of taking r objects out of n objects is


given by:

(a) Determine how many combinations are possible in a lottery game


for selecting 6 numbers that are drawn out of 49.
(b) Using the following formula, determine the probability of guessing
two out of the six drawn numbers.

44 BITS Pilani, Deemed to be University under Section 3, UGC Act


Applications –Lecture 2

clear,
clc
L=0.15;
R=14;
C=2.6e-6;
disp('Part (a)')
number combinations=factorial(49)/(factorial(6)*factorial(49-6))
disp('Part (b)')
chance_of_2=factorial(6)/(factorial(2)*factorial(6-2))* ...
factorial(43)/(factorial(4)*factorial(43-4))/ ...
(factorial(49)/(factorial(6)*factorial(49-6)))

45 BITS Pilani, Deemed to be University under Section 3, UGC Act


BITS Pilani
Hyderabad Campus

MID SEM Revision-Lecture 3


MATLAB-First Program

Physicists tell us that altitude h in feet of a projectile t seconds after firing is

h= -16t2 +vot +h0

where vo is the initial velocity in ft/s and ho is altitude in from which it is fired. If a

rocket is launched from a hilltop 2400 ft above the desert with an initial upward

velocity of 400 ft/s, then when will it land on the desert

47 BITS Pilani, Deemed to be University under Section 3, UGC Act


Practice Problems and Examples-
Homework

2) Change the Current directory to mynewdir. Then open an Edit Window and add the
following lines

% Create an input array from -2*pi to 2*pi

t=-2*pi:pi/10:2*pi
% Calculate |sin(t)|
x=abs(sin(t));
% Plot result
plot(t,x)

48 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 3

Display Options
Matlab Command ratio Comments
format short 50.8333 4 decimal digits
format long 50.83333333333334 14 decimal digits
format short e 5.0833e+001 4 decimal digits plus exponent
format long e 5.083333333333334e+001 14 decimal digits plus exponent
format short g 50.8333 better of format short or
format short e (default), switching for ans > 1000
format long g 5.083333333333334e+001 better of format long or format
long e
format bank 50.83 2 decimal digits
format + positive, negative, or zero

49 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 3

Display Options

Displaying Values and Text


There are three ways to display values and text in Matlab

1. By entering the variable name at the Matlab prompt, without a semicolon.

2. By use of the command disp.

3. By use of the command fprintf

50 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 3

temp=78;
>> disp(temp);
disp(’degrees F’)

output
78
degrees F

fprintf(’format string’, list of variables)

w.d%f Display as fixed point or decimal notation (defaults to short), with a width
of w characters (including the decimal point and possible minus sign, with
d decimal places. Spaces are filled in from the left if necessary. Set d to 0
if you don’t want any decimal places, for example %5.0f. Include leading
zeros if you want leading zeroes in the display, for example %06.0f.

w.d%e Display using scientific notation (defaults to short e), with a width of w
characters (including the decimal point, a possible minus sign, and five for
the exponent), with d digits in the mantissa after the decimal point. The mantissa is always
adjusted to be less than 1.

w.d%g Display using the shorter of tt short or short e format, with width w and d decimal places.
\n Newline (skip to beginning of next line)

51 BITS Pilani, Deemed to be University under Section 3, UGC Act


Algorithm-Calculate the area of the circle

So, the basic algorithm is:


– Get the input: the radius
– Calculate the result: the area
– Display the output

Refining Again
– input can come from various sources (already known / file / user)
• What is the way to take the input from desired source?
– To calculate the area, the formula is needed.
– Output may be given on screen/ file/ announced
• How to show the results from desired source?

52 BITS Pilani, Deemed to be University under Section 3, UGC Act


Algorithm-Calculate the area of the circle

%Matlab
radius = 5
area = pi * (radius^2)

%save this file as


script1.m
and run it on matlab
command prompt, you will
get

>> areacircle
radius =
5
area =
78.5398
>>type areacircle
radius = 5
area = pi * (radius^2)

53 BITS Pilani, Deemed to be University under Section 3, UGC Act


Process of making Matlab Program

Make a flowchart for understanding


Develop an algorithm in the words available in the given programming language.
Translate into a particular programming language.
High-level languages have English-like commands and functions, such as "print
this" or "if x < 5 do something."
The computer, only knows machine language.
Programs that are written in high-level languages must therefore be translated into
machine language to execute.
A program that does this translation from a high-level language to an
executable file is called a compiler. The original program is called the source
code, and the resulting executable program is called the object code.

54 BITS Pilani, Deemed to be University under Section 3, UGC Act


Input and Output

input
disp
fprintf
printing vectors matrices with disp/fprintf

%d integers (it actually stands for decimal integer)


%f floats
%c single characters
%s strings

55 BITS Pilani, Deemed to be University under Section 3, UGC Act


Input and Output

>> mystr = input('Enter a string:', 's')


Enter a string: go
mystr =
go
>> length(mystr)
ans = 6

What would be the result if the user enters blank spaces after other
characters? For example, the user here entered "xyz" (four blank spaces):
>> mychar = input('Enter chars:', 's')
Enter chars: xyz
mychar =
xyz

56 BITS Pilani, Deemed to be University under Section 3, UGC Act


String Inputs

>> x = input('Enter the \nx coordinate:');


Enter the x coordinate: 4

field width can also be included in the placeholder in fprintf

>> fprintf('The int is %3 d and the float is %6.2f\n',… 5,4.9)


The int is 5 and the float is 4.90

That is, %5d would indicate a field width of 5 for printing an integer and
%10s would indicate a field width of 10 for a string.
%6.2f means a field width of 6 (including the decimal point and the
decimal places) with two decimal places.
%.3f indicates three decimal places

TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


Exercises

Write a script that will prompt the user for an angle in degrees. It will then calculate the angle in
radians, and then print the result. Note: π radians = 180°.
Create the following variables:
x = 12.34;
y = 4.56;

Then, fill in the fprintf statements using these variables that will accomplish the
following:

TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus


Discussion Points –Contact Session 4

Problem Solving using MATLAB

Branching Statement
if
if else
Switch

Exercises

59 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

Stainless steel is an alloy of Iron with a minimum of 10.5% Chromium. Chromium produces a
thin layer of oxide on the surface of the steel known as the 'passive layer'. This prevents any
further corrosion of the surface. Increasing the amount of Chromium gives an increased
resistance to corrosion.

Stainless steel also contains varying amounts of Carbon, Silicon and Manganese. Other
elements such as Nickel and Molybdenum may be added to impart other useful properties
such as enhanced formability and increased corrosion resistance.

60 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 3

Alloys composed mostly of aluminium have been very important in aerospace


manufacturing since the introduction of metal-skinned aircraft. Aluminium-magnesium alloys
are both lighter than other aluminium alloys and much less flammable than alloys that contain
a very high percentage of magnesium.[2]

Aluminium alloy surfaces will develop a white, protective layer of aluminium oxide if left
unprotected by anodizing and/or correct painting procedures. In a wet environment, galvanic
corrosion can occur when an aluminium alloy is placed in electrical contact with other metals
with more positive corrosion potentials than aluminium, and an electrolyte is present that
allows ion exchange. Referred to as dissimilar-metal corrosion, this process can occur as
exfoliation or a intergranular corrosion. Aluminium alloys can be improperly heat treated. This
causes internal element separation, and the metal then corrodes from the inside out.

Aluminium alloy compositions are registered with The Aluminum Association. Many
organizations publish more specific standards for the manufacture of aluminium alloy,
including the Society of Automotive Engineers standard organization, specifically its
aerospace standards subgroups,[3] and ASTM International

61 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –MATLAB Problem

Aluminium Alloys are made by adding other elements to aluminium to improve it properties,
such as hardness or tensile strenghth. The following table shows the composition of five
commonly used alloys, which are known by their alloy number. (2204,6061 and so on). Obtain
a matrix algorithm to compute the amounts of raw material needed to produce a given amount
of each alloy. Use MATLAB to determine how much raw material of each type is needed to
produce 1000 tons of each alloy

Composition of Aluminum

Alloy %Cu0 %Mg %Mn %Si %Zn


2024 4.4 1.5 0.6 0 0
6061 0 1 0 0.6 0
7005 0 1.4 0 0 4.5
7075 1.6 2.5 0 0 5.6
356 0 0.3 0 7 0

62 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –MATLAB Problem

% enter composition of Alloyp


p=1000;
a='Cuo';
b='Mg';
c='Mn';
d='Si';
e='zn';
a2024=[4.4,1.5,0.6,0,0];
a6061=[0,1,0,0.6,0];
a7005=[0,1.4,0,0,4.5];
a7075=[1.6,2.5,0,0,5.6];
a356=[0,0.3,0,7,0];
fprintf ('Composition of a2024 % s is %4.2f\n',a,(p*a2024(1)/100))
fprintf ('Composition of a2024 % s is %4.2f\n',b,(p*a2024(2)/100))
fprintf ('Composition of a2024 % s is %4.2f\n',c,(p*a2024(3)/100))
fprintf ('Composition of a2024 % s is %4.2f\n',d,(p*a2024(4)/100))
fprintf ('Composition of a2024 % s is %4.2f\n',e,(p*a2024(5)/100))
fprintf ('\nComposition of a6061 % s is %4.2f\n',a,(p*a6061(1)/100))
fprintf ('Composition of a6061 % s is %4.2f\n',b,(p*a6061(2)/100))
fprintf ('Composition of a6061 % s is %4.2f\n',c,(p*a6061(3)/100))
fprintf ('Composition of a6061 % s is %4.2f\n',d,(p*a6061(4)/100))
fprintf ('Composition of a6061 % s is %4.2f\n',e,(p*a6061(5)/100))

)
63 BITS Pilani, Deemed to be University under Section 3, UGC Act
Discussion Points –MATLAB Problem

fprintf ('\nComposition of a7075 % s is %4.2f\n',a,(p*a7075(1)/100))


fprintf ('Composition of a7075 % s is %4.2f\n',b,(p*a7075(2)/100))
fprintf ('Composition of a7075 % s is %4.2f\n',c,(p*a7075(3)/100))
fprintf ('Composition of a7075 % s is %4.2f\n',d,(p*a7075(4)/100))
fprintf ('Composition of a7075 % s is %4.2f\n',e,(p*a7075(5)/100))

fprintf ('\nComposition of a7005 % s is %4.2f\n',a,(p*a7005(1)/100))


fprintf ('Composition of a7005 % s is %4.2f\n',b,(p*a7005(2)/100))
fprintf ('Composition of a7005 % s is %4.2f\n',c,(p*a7005(3)/100))
fprintf ('Composition of a7005 % s is %4.2f\n',d,(p*a7005(4)/100))
fprintf ('Composition of a7005 % s is %4.2f\n',e,(p*a7005(5)/100))

fprintf ('\nComposition of a356 % s is %4.2f\n',a,(p*a356(1)/100))


fprintf ('Composition of a356 % s is %4.2f\n',b,(p*a356(2)/100))
fprintf ('Composition of a356 % s is %4.2f\n',c,(p*a356(3)/100))
fprintf ('Composition of a356 % s is %4.2f\n',d,(p*a356(4)/100))
fprintf ('Composition of a356 % s is %4.2f\n',e,(p*a356(5)/100)
)

64 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –MATLAB Problem

Composition of a2024 Cuo is 44.00 Composition of a356 Cuo is 0.00 Composition of a7005 Cuo is 0.00
Composition of a2024 Mg is 15.00 Composition of a356 Mg is 3.00 Composition of a7005 Mg is 14.00
Composition of a2024 Mn is 6.00 Composition of a356 Mn is 0.00 Composition of a7005 Mn is 0.00
Composition of a2024 Si is 0.00 Composition of a356 Si is 70.00 Composition of a7005 Si is 0.00
Composition of a2024 zn is 0.00 Composition of a356 zn is 0.00 Composition of a7005 zn is 45.00
>> Alloy
Composition of a2024 Cuo is 44.00 Composition of a356 Cuo is 0.00
Composition of a6061 Cuo is 0.00
Composition of a2024 Mg is 15.00 Composition of a356 Mg is 3.00
Composition of a6061 Mg is 10.00
Composition of a2024 Mn is 6.00 Composition of a356 Mn is 0.00
Composition of a6061 Mn is 0.00
Composition of a2024 Si is 0.00 Composition of a356 Si is 70.00
Composition of a6061 Si is 6.00 Composition of a2024 zn is 0.00 Composition of a356 zn is 0.00
Composition of a6061 zn is 0.00
Composition of a6061 Cuo is 0.00
Composition of a7075 Cuo is 16.00 Composition of a6061 Mg is 10.00
Composition of a7075 Mg is 25.00 Composition of a6061 Mn is 0.00
Composition of a7075 Mn is 0.00 Composition of a6061 Si is 6.00
Composition of a7075 Si is 0.00 Composition of a6061 zn is 0.00
Composition of a7075 zn is 56.00
Composition of a7075 Cuo is 16.00
Composition of a7005 Cuo is 0.00
Composition of a7075 Mg is 25.00
Composition of a7075 Mn is 0.00
Composition of a7005 Mg is 14.00
Composition of a7075 Si is 0.00
Composition of a7005 Mn is 0.00
Composition of a7075 zn is 56.00
Composition of a7005 Si is 0.00
Composition of a7005 zn is 45.00

65 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

Homework Problems

66 BITS Pilani, Deemed to be University under Section 3, UGC Act


OBJECTIVES-Logical Data Types

• The Logical Data Type


• Relational Operators (==, ~=, >, < , >=, <=)
• Logic Operators (&, &&, |, ||, xor, ~)
• Logical Functions (ischar, isempty, ….)
• Branches
• (if-else) Statement
• switch Statement
• try-catch Statement
• Additional Plotting Features

67 BITS Pilani, Deemed to be University under Section 3, UGC Act


THE LOGICAL DATA TYPE (true, false)

68 BITS Pilani, Deemed to be University under Section 3, UGC Act


RELATIONAL OPERATORS (==, ~=, >, < , >=, <=)

Some relational operations


and their results

69 BITS Pilani, Deemed to be University under Section 3, UGC Act


RELATIONAL OPERATORS (==, ~=, >, < , >=, <=)

Compare array Compare array by Be careful because of


by a value
another one (of the roundoff errors
same size)

70 BITS Pilani, Deemed to be University under Section 3, UGC Act


LOGIC OPERATORS

Operator Operation
& Logical AND (scalar/array, both sides evaluation)
&& Logical AND (scalar, left then right side evaluation)
| Logical inclusive OR (scalar/array both sides evaluation)

|| Logical inclusive OR (scalar, left then right side evaluation)

xor Logical exclusive OR


~ Logical NOT

71 BITS Pilani, Deemed to be University under Section 3, UGC Act


LOGIC OPERATORS

72 BITS Pilani, Deemed to be University under Section 3, UGC Act


LOGICAL Functions

73 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 3

Syntax of Switch Statement

Switch <switch_expression>

case <case_expression> <statements>

case <case_expression> <statements> ... ...

otherwise <statements>

end

74 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

Syntax of If Statements

grade = 'B';
switch(grade)
case 'A' fprintf('Excellent!\n' );
case 'B' fprintf('Well done\n' );
case 'C' fprintf('Well done\n' );
case 'D' fprintf('You passed\n' );
case 'F' fprintf('Better try again\n' );
otherwise fprintf('Invalid grade\n' );
end

75 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 3

x = 6.1;
units = ’ft’;
% convert x to meters
switch units
case {’inch’,’in’}
164
y = x*0.0254;
case{’feet’,’ft’}
y = x*0.3048;
case{’meter’,’m’}
y = x;
case{’centimeter’,’cm’}
y = x/100;
case{’millimeter’,’mm’}
y = x/1000;
otherwise
disp([’Unknown units: ’ units])
y = NaN;
end

76 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 3

Syntax of If Statements

77 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 3

a = 10; % check the condition using if statement


if a < 20 % if condition is true then print the following f
printf('a is less than 20\n' );
end
fprintf('value of a is : %d\n', a);

a = 100; % check the boolean condition


if a < 20 % if condition is true then print the following
fprintf('a is less than 20\n' );
else % if condition is false then print the following
fprintf('a is not less than 20\n' );
end
fprintf('value of a is : %d\n', a);

78 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 3

Example 3: while Loop

a = 10; % while loop execution


while( a < 20 )
fprintf('value of a: %d\n', a);
a = a + 1;
End

Example 4 : For Loop

for a = 10:20
fprintf('value of a: %d\n', a);
End

for a = 1.0: -0.1: 0.0


disp(a)
end

79 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 3

for m = 1:j
for n = 1:k
<statements>; end
End

while <expression1>
while <expression2>
<statements> end
end

80 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 3

for i=2:100

for j=2:100

if(~mod(i,j))

break; % if factor found, not prime

end

end

if(j > (i/j))

fprintf('%d is prime\n', i);

end

end

81 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 3

% Script to compute ax^2 +bx + c


disp(’Quadratic ax^2+bx+c evaluated’)
disp(’for user input a, b, c, and x’)
a=1; b=1; c=1; x=0;
while a~=0 | b~=0 | c~=0 | x~=0
disp(’Enter a=b=c=x=0 to terminate’)
a = input(’Enter value of a: ’);
b = input(’Enter value of b: ’);
c = input(’Enter value of c: ’);
x = input(’Enter value of x: ’);
if a==0 & b==0 & c==0 & x==0
break
end
quadratic = a*x^2 + b*x + c;
disp(’Quadratic result:’)
disp(quadratic)
end

82 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

A can of soda at temperature 25 ◦ C is placed in a refrigerator, where the


ambient temperature F is 10 ◦ C. We want to determine how the
temperature of the soda changes over a period of time. A standard way of
approaching this type of problem is to subdivide the time interval into a
number of small steps, each of duration ∆t. If T i is the temperature at the
beginning of step i, the following model can be used to determine T i+1 :
T i+1 = T i + K∆t(F − T i ) where K is the conduction coefficient, a
parameter that depends on the insulating properties of the can and the
thermal properties of the soda. Assume that units are chosen so that time
is in minutes and that an interval ∆t = 1 minute provides sufficient
accuracy. A script to compute, display, and plot this update process for K
= 0.05:

83 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 3

% Define input values


K = 0.05; % Conduction coefficient
F = 10; % Refrigerator temperature (degrees C)
% Define vector variables
t = 0:100; % Time variable (min)
T = zeros(1,101); % Preallocate temperature vector
T(1) = 25; % Initial soda temperature (degrees C)
% Update to compute T
for i = 1:100; % Time in minutes
T(i+1) = T(i) + K * (F - T(i)); % Compute T
end
% Display results every 10 minutes, plot every minute
disp([ t(1:10:101)’ T(1:10:101)’ ])
plot(t,T),grid,xlabel(’Time (min)’),ylabel(’Temperature (degrees C)’),...
title(’Cooling curve’)

84 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 3

Suppose that you have a 20,000 loan at 6 percent annual interest compounded
monthly. You can afford to pay 200/month toward this loan. How long will it take
until the loan is paid off? To do this calculation, think of the amount remaining on
the loan from time k to time k+1 as a combination of interest accrued and payment
made, express this as an iteration, and then write code using a for loop to find the
amount remaining in the loan after N months. You may need to experiment with the
value of N to find the value in which the remaining amount passes through zero
(and the loan is paid off).

85 BITS Pilani, Deemed to be University under Section 3, UGC Act


BITS Pilani
Hyderabad Campus

MID SEM Revision-Lecture 4


Discussion Points –Contact Session 4

Recap of the Previous Sessions:- Commands


abs(s) – Signifies the magnitude of the number
angle(X)- Phase angle of a complex number x=a+bj , tan-1(b/a)
angle(2-3i)=-0.9828
ceil(x) – smallest integer greater than the real number – ceil(2.36)-3
conj(x)- complex conjugate of a complex number- conj(a+ib)
exp(x)-exp(5)
factorial-factorial of a given number – factorial(8)
floor-floor(2.36)-----2
fix-fix(2.35)--2
imag—imaginary part of a complex number
isprime-isprime(x)---It returns 1 if x is a prime
log2(x)-logarithm of base 2
mod(x,y)-remainder when x is divided by y
rand- generates number from 0-1
randn-generates range from -1 to 1

87 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

7+6
format short , long, bank

Live Practice Session- Watch Video

 Accessing a Particular Elemnt


 Accessing two or more elements
 : Operator
 end command
 linspace
 Expanding and reducing array
88 BITS Pilani, Deemed to be University under Section 3, UGC Act
Discussion Points –Contact Session 4

Length and Size functions


Reversing element of an array
Sorting an Arrar

Addition
Multiplication
conv(x,y)

deconv(x,y)
kron (x,y)
cumsum(x)
cumprod(x)

89 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

max(x)
mean(x)
transpose(x)
std(x)
fliplr(x)
flipdim(x)
size(x)
var(x)
find(x>4)

90 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

Problem Solving using MATLAB

Branching Statement
if
if else
Switch

Exercises

91 BITS Pilani, Deemed to be University under Section 3, UGC Act


OBJECTIVES-Logical Data Types

• The Logical Data Type


• Relational Operators (==, ~=, >, < , >=, <=)
• Logic Operators (&, &&, |, ||, xor, ~)
• Logical Functions (ischar, isempty, ….)
• Branches
• (if-else) Statement
• switch Statement
• try-catch Statement
• Additional Plotting Features

92 BITS Pilani, Deemed to be University under Section 3, UGC Act


THE LOGICAL DATA TYPE (true, false)

93 BITS Pilani, Deemed to be University under Section 3, UGC Act


RELATIONAL OPERATORS (==, ~=, >, < , >=, <=)

Some relational operations


and their results

94 BITS Pilani, Deemed to be University under Section 3, UGC Act


RELATIONAL OPERATORS (==, ~=, >, < , >=, <=)

Compare array Compare array by Be careful because of


by a value
another one (of the roundoff errors
same size)

95 BITS Pilani, Deemed to be University under Section 3, UGC Act


LOGIC OPERATORS

Operator Operation
& Logical AND (scalar/array, both sides evaluation)
&& Logical AND (scalar, left then right side evaluation)
| Logical inclusive OR (scalar/array both sides evaluation)

|| Logical inclusive OR (scalar, left then right side evaluation)

xor Logical exclusive OR


~ Logical NOT

96 BITS Pilani, Deemed to be University under Section 3, UGC Act


LOGIC OPERATORS

97 BITS Pilani, Deemed to be University under Section 3, UGC Act


LOGICAL Functions

98 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

Syntax of Switch Statement

Switch <switch_expression>

case <case_expression> <statements>

case <case_expression> <statements> ... ...

otherwise <statements>

end

99 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

Syntax of If Statements

grade = 'B';
switch(grade)
case 'A' fprintf('Excellent!\n' );
case 'B' fprintf('Well done\n' );
case 'C' fprintf('Well done\n' );
case 'D' fprintf('You passed\n' );
case 'F' fprintf('Better try again\n' );
otherwise fprintf('Invalid grade\n' );
end

100 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

x = 6.1;
units = ’ft’;
% convert x to meters
switch units
case {’inch’,’in’}
164
y = x*0.0254;
case{’feet’,’ft’}
y = x*0.3048;
case{’meter’,’m’}
y = x;
case{’centimeter’,’cm’}
y = x/100;
case{’millimeter’,’mm’}
y = x/1000;
otherwise
disp([’Unknown units: ’ units])
y = NaN;
end

101 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

Syntax of If Statements

102 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

a = 10; % check the condition using if statement


if a < 20 % if condition is true then print the following f
printf('a is less than 20\n' );
end
fprintf('value of a is : %d\n', a);

a = 100; % check the boolean condition


if a < 20 % if condition is true then print the following
fprintf('a is less than 20\n' );
else % if condition is false then print the following
fprintf('a is not less than 20\n' );
end
fprintf('value of a is : %d\n', a);

103 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

Example 3: while Loop

a = 10; % while loop execution


while( a < 20 )
fprintf('value of a: %d\n', a);
a = a + 1;
End

Example 4 : For Loop

for a = 10:20
fprintf('value of a: %d\n', a);
End

for a = 1.0: -0.1: 0.0


disp(a)
end

104 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

for m = 1:j
for n = 1:k
<statements>; end
End

while <expression1>
while <expression2>
<statements> end
end

105 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

for i=2:100

for j=2:100

if(~mod(i,j))

break; % if factor found, not prime

end

end

if(j > (i/j))

fprintf('%d is prime\n', i);

end

end

106 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

% Script to compute ax^2 +bx + c


disp(’Quadratic ax^2+bx+c evaluated’)
disp(’for user input a, b, c, and x’)
a=1; b=1; c=1; x=0;
while a~=0 | b~=0 | c~=0 | x~=0
disp(’Enter a=b=c=x=0 to terminate’)
a = input(’Enter value of a: ’);
b = input(’Enter value of b: ’);
c = input(’Enter value of c: ’);
x = input(’Enter value of x: ’);
if a==0 & b==0 & c==0 & x==0
break
end
quadratic = a*x^2 + b*x + c;
disp(’Quadratic result:’)
disp(quadratic)
end

107 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

A can of soda at temperature 25 ◦ C is placed in a refrigerator, where the


ambient temperature F is 10 ◦ C. We want to determine how the
temperature of the soda changes over a period of time. A standard way of
approaching this type of problem is to subdivide the time interval into a
number of small steps, each of duration ∆t. If T i is the temperature at the
beginning of step i, the following model can be used to determine T i+1 :
T i+1 = T i + K∆t(F − T i ) where K is the conduction coefficient, a
parameter that depends on the insulating properties of the can and the
thermal properties of the soda. Assume that units are chosen so that time
is in minutes and that an interval ∆t = 1 minute provides sufficient
accuracy. A script to compute, display, and plot this update process for K
= 0.05:

108 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

% Define input values


K = 0.05; % Conduction coefficient
F = 10; % Refrigerator temperature (degrees C)
% Define vector variables
t = 0:100; % Time variable (min)
T = zeros(1,101); % Preallocate temperature vector
T(1) = 25; % Initial soda temperature (degrees C)
% Update to compute T
for i = 1:100; % Time in minutes
T(i+1) = T(i) + K * (F - T(i)); % Compute T
end
% Display results every 10 minutes, plot every minute
disp([ t(1:10:101)’ T(1:10:101)’ ])
plot(t,T),grid,xlabel(’Time (min)’),ylabel(’Temperature (degrees C)’),...
title(’Cooling curve’)

109 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 4

Suppose that you have a 20,000 loan at 6 percent annual interest compounded
monthly. You can afford to pay 200/month toward this loan. How long will it take
until the loan is paid off? To do this calculation, think of the amount remaining on
the loan from time k to time k+1 as a combination of interest accrued and payment
made, express this as an iteration, and then write code using a for loop to find the
amount remaining in the loan after N months. You may need to experiment with the
value of N to find the value in which the remaining amount passes through zero
(and the loan is paid off).

110 BITS Pilani, Deemed to be University under Section 3, UGC Act


BITS Pilani
Hyderabad Campus

MID SEM Revision-Lecture 5


Discussion Points –Contact Session 5

Branching Statement
if
if else
Switch

Exercises

112 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 5

Branching Statement
if
if else
Switch

Exercises

113 BITS Pilani, Deemed to be University under Section 3, UGC Act


Problem Solving Approach

1. Generate 100 Fibonnacci series

2. Generate 100 Prime Number

3. Find the largest number from 100 numbers

4. Solve the following three numbers

-4x+3y+z=-18.2
5x+6y -2z=-48.8
2x-5y+4.5z=92.5

114 BITS Pilani, Deemed to be University under Section 3, UGC Act


Problem Solving Approach

115 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 5

% To print 100 fibinnacci


numbers
f1=1;
f2=1;
fprintf('%f %f',f1,f2);
for i=2:100 Flow Control
f3=f1+f2;
fprintf('%f',f3);
f1=f2;
f2=f3;
end

116 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 5

%To print Prime Numbers from 1 -100


clear;
clc;
for i=2:50
for j=2:50
if ~ mod(i,j)
Flow Control
break;
else
if (j>(i/j))
fprintf('The number is prime=%d',i);
end
end
end
end

117 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 5

3. Find the largest number from 100 numbers

4.
-4x+3y+z=-18.2
5x+6y -2z=-48.8
2x-5y+4.5z=92.5

Solve yourself

118 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 5

119 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 5

x = 100;
y = -10;

if x < 50 %test to see if x is less than 50


z = x – y^2;
A = x + 12.5*y + z^3;
end

for i=1:3 %executes three times


x=i^2
end

120 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 5

Syntax of If Statements

grade = 'B';
switch(grade)
case 'A' fprintf('Excellent!\n' );
case 'B' fprintf('Well done\n' );
case 'C' fprintf('Well done\n' );
case 'D' fprintf('You passed\n' );
case 'F' fprintf('Better try again\n' );
otherwise fprintf('Invalid grade\n' );
end

121 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 5

x = 6.1;
units = ’ft’;
% convert x to meters
switch units
case {’inch’,’in’}
164
y = x*0.0254;
case{’feet’,’ft’}
y = x*0.3048;
case{’meter’,’m’}
y = x;
case{’centimeter’,’cm’}
y = x/100;
case{’millimeter’,’mm’}
y = x/1000;
otherwise
disp([’Unknown units: ’ units])
y = NaN;
end

122 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 5

Syntax of If Statements

123 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 5

% Script to compute ax^2 +bx + c


disp(’Quadratic ax^2+bx+c evaluated’)
disp(’for user input a, b, c, and x’)
a=1; b=1; c=1; x=0;
while a~=0 | b~=0 | c~=0 | x~=0
disp(’Enter a=b=c=x=0 to terminate’)
a = input(’Enter value of a: ’);
b = input(’Enter value of b: ’);
c = input(’Enter value of c: ’);
x = input(’Enter value of x: ’);
if a==0 & b==0 & c==0 & x==0
break
end
quadratic = a*x^2 + b*x + c;
disp(’Quadratic result:’)
disp(quadratic)
end

124 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 5

A can of soda at temperature 25 ◦ C is placed in a refrigerator, where the


ambient temperature F is 10 ◦ C. We want to determine how the
temperature of the soda changes over a period of time. A standard way of
approaching this type of problem is to subdivide the time interval into a
number of small steps, each of duration ∆t. If T i is the temperature at the
beginning of step i, the following model can be used to determine T i+1 :
T i+1 = T i + K∆t(F − T i ) where K is the conduction coefficient, a
parameter that depends on the insulating properties of the can and the
thermal properties of the soda. Assume that units are chosen so that time
is in minutes and that an interval ∆t = 1 minute provides sufficient
accuracy. A script to compute, display, and plot this update process for K
= 0.05:

125 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 5

% Define input values


K = 0.05; % Conduction coefficient
F = 10; % Refrigerator temperature (degrees C)
% Define vector variables
t = 0:100; % Time variable (min)
T = zeros(1,101); % Preallocate temperature vector
T(1) = 25; % Initial soda temperature (degrees C)
% Update to compute T
for i = 1:100; % Time in minutes
T(i+1) = T(i) + K * (F - T(i)); % Compute T
end
% Display results every 10 minutes, plot every minute
disp([ t(1:10:101)’ T(1:10:101)’ ])
plot(t,T),grid,xlabel(’Time (min)’),ylabel(’Temperature (degrees C)’),...
title(’Cooling curve’)

126 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 5

Suppose that you have a 20,000 loan at 6 percent annual interest compounded
monthly. You can afford to pay 200/month toward this loan. How long will it take
until the loan is paid off? To do this calculation, think of the amount remaining on
the loan from time k to time k+1 as a combination of interest accrued and payment
made, express this as an iteration, and then write code using a for loop to find the
amount remaining in the loan after N months. You may need to experiment with the
value of N to find the value in which the remaining amount passes through zero
(and the loan is paid off).

127 BITS Pilani, Deemed to be University under Section 3, UGC Act


Discussion Points –Contact Session 5

MATLAB also has a built-in function called menu that will display a Figure Window with push

buttons for the choices. The first string passed to the menu function is the heading, and the

rest are labels that appear on the push buttons. The function returns the number of the button

that is pressed. For example,

>> mypick= menu(‘Pick a pizza’,‘Cheese’,‘Shroom’,‘Sausage’);


%This script asks the user for a type of pizza and prints which type to order using a switch
mypick = menu(‘Pick a pizza’,‘Cheese’,‘Shroom’,‘Sausage’);
switch mypick
case 1
disp(‘Order a cheese pizza’)
case 2
disp(‘Order a mushroom pizza’)
case 3
disp(‘Order a sausage pizza’)
otherwise
disp(‘No pizza for us today’)
end

128 BITS Pilani, Deemed to be University under Section 3, UGC Act


PLOTS -3 D

129 BITS Pilani, Deemed to be University under Section 3, UGC Act


MATLAB-3 D Plots

t = datetime(2014,6,28) +calweeks(0:9);
y = rand(1,10);
plot(t,y);

t = datetime('today') + caldays(1:100);
y = linspace(10,40,100) + 10*rand(1,100);
scatter(t,y)

130 BITS Pilani, Deemed to be University under Section 3, UGC Act


MATLAB-3 D Plots

contour Contour plot.

contour(Z) draws a contour plot of matrix Z in the x-y plane, with


the x-coordinates of the vertices corresponding to column indices
of Z and the y-coordinates corresponding to row indices of Z. The
contour levels are chosen automatically.

x = linspace(-2*pi,2*pi);
y = linspace(0,4*pi);
[X,Y] = meshgrid(x,y);
Z = sin(X)+cos(Y);
figure
contour(X,Y,Z)

131 BITS Pilani, Deemed to be University under Section 3, UGC Act


MATLAB-3 D Plots

x = -2:0.2:2;
y = -2:0.2:3;
[X,Y] = meshgrid(x,y);
Z = X.*exp(-X.^2-Y.^2); f
figure
contour(X,Y,Z,'ShowText','on')

132 BITS Pilani, Deemed to be University under Section 3, UGC Act


MATLAB-Examples

mesh(X,Y,Z) draws a wireframe mesh with color determined by Z, so color is proportional to


surface height. If X and Y are vectors, length(X) = n and length(Y) = m,

where[m,n] = size(Z). In this case, (X(j), Y(i), Z(i,j)) are the intersections of the wireframe
grid lines; X and Y correspond to the columns and rows of Z, respectively. If X and Y are
matrices, (X(i,j), Y(i,j), Z(i,j)) are the intersections of the wireframe grid lines. The values
in X, Y, or Z can be numeric, datetime, duration, or categorical values.

mesh(Z) draws a wireframe mesh using X = 1:n and Y = 1:m, where [m,n] = size(Z). The
height, Z, is a single-valued function defined over a rectangular grid. Color is proportional to
surface height. The values in Z can be numeric, datetime, duration, or categorical values

133 BITS Pilani, Deemed to be University under Section 3, UGC Act


MATLAB-Examples

[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R; f
figure
mesh(Z)

134 BITS Pilani, Deemed to be University under Section 3, UGC Act


MATLAB-Examples

[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R; f
igure
mesh(Z)

135 BITS Pilani, Deemed to be University under Section 3, UGC Act


MATLAB-Examples

surf(X,Y,Z) creates a three-dimensional surface plot. The function plots the


values in matrix Z as heights above a grid in the x-y plane defined by X and Y.
The function also uses Z for the color data, so color is proportional to height.

[X,Y] = meshgrid(1:0.5:10,1:20);
Z = sin(X) + cos(Y);
surf(X,Y,Z)

136 BITS Pilani, Deemed to be University under Section 3, UGC Act


User Defined Functions

Top down Design

Independent testing of sun tasks

Reusable Code

Isolation from unintended side effects

137 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Format

function [outarg1,outarg2,…..]=fname (inarg1,inarg2,……)

% H1 comment line
% other comment line

(executable code)

(return)

(end)

138 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Example-1
function distance=dist2(x1,y1,x2,y2)

% calculates the distance between the two points


%(x1,y1) and (x2,y2) in Cartesian coordinate system
% calling sequence:
%distance=dist2(x1,y1,x2,y2)
%define variables
% x1---x position of point 1
% x2---x position of point 2
% y1---y position of point 1
% y1---y position of point 2
% distance –Distance between points
% Calculate distance
distance=sqrt((x2-x1).^2+(y2-y1).^2);
end

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


You can execute all of the lines of the file (sequentially) by typing the filename at
the MATLAB prompt.

If filename is computetraj.m, then

>> computetraj

causes the instructions (ie., the MATLAB commands) in the file to be run.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Basics
– Function declaration line (3)
– Input and output arguments (3)
– Call by value, but with delayed copy (2)
– Function workspaces, recursion, towers example (7)
– Special features (4)
• nargin, nargout, varargin, varargout, assignin, evalin

Subfunctions (4)
Nested functions (4)
Anonymous functions (4)
Function_handles (4)

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Suppose a file called runthis.m contains the text

X = linspace(0,4*pi,1000);
Y = sin(3*X) + 2*cos(5*X);
plot(X,Y)
maxy = max(abs(Y));
disp([’Peak of Y is ’\ num2str(maxy)]);
Script file example

Then, typing
>> runthis
will cause the 5 lines to execute, resulting in a plot
and a message about the peak value of Y.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Then,everytimeyouneedtoexecutethattask,youwillonlyneedto“call”thefunction.

FUNCTIONS in programming
Thismodularityhelpsbreakdownahugeprogramtaskintoacollectionofsmallertasks,whichindividuallyareeasiertodesign,write,debugandmaintain.

functionsaresometiIfyouhavea“complex”task(eg.,morethantwolinesofMatlabprogramcode)thatyouwillreuseinafew(orseveralplaces),youwillwanttowritethat
In mathematics, a function is a rule that assigns to each value of
the input, a corresponding output value.
taskasareusablefunctionfile.

Consider the function f defined by the rule


mesalsocalledsubroutines,methods,etc.

f(x) = x2 for all numbers x.


Here, x is the input value, and f(x) is the output value.

Equivalently, we could have written the rule as


f(y) = y2 for all numbers y.

Functions can have many inputs and produce (through multiple


rules) many outputs, f1(a,b,c) = 2a+3b, f2(a,b,c) = bc.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


FUNCTIONS in programming
Then,everytimeyouneedtoexecutethattask,youwillonlyneedto“call”thefunction.

If you have
Thismodularity a down
helpsbreak “complex”
ahugeprogramtaskintotask (eg.,
acollectionofsmallertasks,more than
whichindividuallyareeasiertotwo lines
design,write, of Matlab program code) that
debugandmaintain.
you will reuse in a few (or several places), you will want to write that task as a
reusable function file.
functionsare
Example: trigonometric SIN function

Then, every time you need to execute that task, you will only need to “call” the
function.

This modularity helps break down a huge program task into a collection of smaller
tasks, which individually are easier to design, write, debug and maintain.

functions are sometimes also called subroutines, methods, etc.

function volume =
volume_sphere(radius)
volume=4/3*pi.*(radius^3);
end

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


FUNCTIONS in programming
Then,everytimeyouneedtoexecutethattask,youwillonlyneedto“call”thefunction.

Thismodularityhelpsbreakdownahugeprogramtaskintoacollectionofsmallertasks,whichindividuallyareeasiertodesign,write,debugandmaintain.

The The first line is the function declaration line first line is the function
declaration line.
functionsare
The input variables. This
function [dp,cp] = vecop(v,w) function has two. Within
the function, the names
The output variables. This of the input variables are
function has two. The v and w.
function’s purpose is to
compute these variables,
based on the values of the
input variables.
The function name, this function
should be saved in a file called
vecop.m

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


6-line function in vecop.m

Function declaration line

function [dp,cp] = vecop(v,w)


dp = sum(v.*w);
cp = zeros(3,1);
cp(1) = v(2)*w(3) – w(2)*v(3);
cp(2) = v(3)*w(1) – w(3)*v(1);
cp(3) = v(1)*w(2) – w(1)*v(2);
Logically correct expressions and assignments that compute the output
variables using the values of the input variables.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


function [dp,cp] = vecop2(v,w)
% VECOP computes dot product and cross
% product of two 3-by-1 vectors.

comments
dp = sum(v.*w);

cp = zeros(3,1); % create 3-by-1


% Fill cp
cp(1) = v(2)*w(3) – w(2)*v(3);
cp(2) = v(3)*w(1) – w(3)*v(1);
cp(3) = v(1)*w(2) – w(1)*v(2);
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Calling a function

• >>
• >> v1 = [1;-2;3];
• >> v2 = [0;1;1];
• >> [A,B] = vecop(v1,v2);
function [dp,cp] = vecop(v,w)
• >>
BASE WORKSPACE FUNCTION INSTANCE WS
dp = sum(v.*w);
v1 3-by-1
v 3-by-1
cp = zeros(3,1); dp 1-by-1
v2 3-by-1
cp 3-by-1
A 1-by-1 cp(1) w= 3-by-1
v(2)*w(3)-w(2)*v(3);
B 3-by-1 cp(2) = v(3)*w(1)-w(3)*v(1);
cp(3) = v(1)*w(2)-w(1)*v(2);
TA ZC -164 Jan 12nd 2019 L-1 BITS Pilani, Pilani Campus
function [mean,std_dev1]= standarddeviation(v)
sum=0;
cumsum=0;
for i=1:numel(v)
mean=sum+v(i)/numel(v);
sum=mean;
std_dev1=cumsum+sqrt(v(i)-mean)^2/numel(v);
cumsum=std_dev1;
end
end

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


MATLAb-Electrical Circuits

Figure below shows an electrical circuit with resistors and voltage sources. Write a
MATLAB program to determine the current in each resistor using the mesh current
method based on Kirchhoff’s voltage law.

Given: V1 = 22 V, V2 = 12 V, V3 = 44 V, R1 = 20 , R2 = 12 , R3 = 15 , R4 = 7 , R5 =
16 , R6 = 10 ,R7 = 10 , R8 = 15 

150 BITS Pilani, Deemed to be University under Section 3, UGC Act


MATLAb-Electrical Circuits

151 BITS Pilani, Deemed to be University under Section 3, UGC Act


Solution in MATLAB

%INITIALIZING THE VARIABLES


V1=22;
V2=12;
V3=44;
V=[–V1;0;V2;–V3]%CREATE THE VOLTAGE VECTOR
R1=20;
R2=12;
R3=15;
R4=7;
R5=16;
R6=10;
R7=10;
R8=15;
% CREATE THE RESISTANCE MATRIX
R=[–(R1+R2+R3) R2 R3 0;
R2 –(R2+R4+R5+R7) R4 R7;
R3 R4 –(R3+R4+R6)R6;
0 R7 R6 –(R6+R7+R8)];
% GET THE CURRENT VECTOR AS SOLUTION
I=inv(R)*V;
% ALLOT VALUES TO FOUR CURRENTS
i1=I(1)
i2=I(2)
i3=I(3)
i4=I(4)

152 BITS Pilani, Deemed to be University under Section 3, UGC Act


BITS Pilani
Hyderabad Campus

MID SEM Revision-Lecture 6 contd and


7
Format

function [outarg1,outarg2,…..]=fname (inarg1,inarg2,……)

% H1 comment line
% other comment line

(executable code)

(return)

(end)

154 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Calculate mean and Standard deviation using
Function

function [mean,std_dev1]= standarddeviation(v)


sum=0;
cumsum=0;
for i=1:numel(v)
mean=sum+v(i)/numel(v);
sum=mean;
std_dev1=cumsum+sqrt(v(i)-mean)^2/numel(v);
cumsum=std_dev1;
end
end

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Efficiency of Turbine Calculation using function

1. Calculate the efficiency of a power plant using function in MATLAB if the


efficiencies of the boiler, turbine and generator are 88, 40 and 98%, respectively.
Write the function as general so that for varying efficiency it should calculate
the overall efficiency. Formula to calculate the efficiency is
Epower plant = [Eboiler] *[Eturbine] * [Egenerator]

function total_eff=eff(x,y,z)
x=input('Boiler efficiency in
fraction');
y=input('turbine efficiency in
fraction');
z=input('generator efficiency in
fraction');
total_eff=x*y*z;

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Ideal Air Efficiency Problem

Create a function in MATLAB to calculate the ideal air standard cycle efficiency
based on the Otto cycle for a gas engine with a cylinder bore of 50 mm, a stroke of
75 mm and a clearance volume of 21.3 cm3.Take the inputs as Cylinder bore,
clearance volume and get the outputs of compression ratio and efficiency. The
calculations are done as follows in the snapshot

157 BITS Pilani, Deemed to be University under Section 3, UGC Act


Ideal Air Efficiency Problem-Analytical Solution

158 BITS Pilani, Deemed to be University under Section 3, UGC Act


Ideal Air Efficiency Problem-MATLAB function
Solution

function Efficiency=ottocycle(d,S,VC)
% d is bore diameter ENTER IN MM
% S is stroke ENTER IN MM
%VC is clearance volume ENTER IN MM3
VS=(pi*d^2*S/4)*(1/1000) ;% conversion to cm
disp(VS);
r=(VC+VS)/VC; % no difference in unit as units are
same
disp(r);
Efficiency=(1- (1/(r^0.4)))*100;

159 BITS Pilani, Deemed to be University under Section 3, UGC Act


Practice Problems

Find the mass flow rate of the liquid in lb/min flowing through a pipe of 5 cm
diameter which has density of 960 kg/m3 and viscosity 0.9 centipoise. The
Reynolds number is reported to be
3200 for the flow.

Steam is flowing at the rate of 2000 kg/h in a 3 NB, 40 schedule pipe at 440
kPa absolute and 453 K. Calculate the velocity of the steam in the pipeline.

160 BITS Pilani, Deemed to be University under Section 3, UGC Act


Practice Problems

1. Find the mass flow rate of the liquid in lb/min flowing through a pipe of 5 cm
diameter which has density of 960 kg/m3 and viscosity 0.9 centipoise. The Reynolds
number is reported to be 3200 for the flow.

2. Corrosion rate are normally reported in miles per year (mpy) in the chemical process
industry. For the measurement of the rate, a corrosion test coupon is inserted in the
process stream for a definite period. The loss of weight is measured during the period
of insertion. In a particular test, a coupon of carbon steel was kept in a cooling water
circuit. The dimensions of the coupon were measured to be 7.5 cm × 1.3 cm × 0.15 cm.
Weight of the coupon before insertion in the circuit and after exposure for 50 days
were measured to be 15 g and 14.6 g respectively. Calculate the rate of corrosion. Take
the density of the carbon steel = 7.754 g/cm3.
Note: 1 mpy = 0.001 in per year. [Ans. 5.3 mpy].

161 BITS Pilani, Deemed to be University under Section 3, UGC Act


Function and Logic

a= 1.3;
b = .2;
c = 30;
parabola = @(x) a*x.^2 + b*x + c;

abc
Clear
x = 1;
y = parabola(x)

162 BITS Pilani, Deemed to be University under Section 3, UGC Act


Function and Logic

myfunction = @(x,y) (x^2 + y^2 + x*y);

x = 1;
y = 10;

z = myfunction(x,y)

g = inline('t^2')
g=
g(t) = t^2

f = inline('3*sin(2*x.^2)')

163 BITS Pilani, Deemed to be University under Section 3, UGC Act


Function and Logic-
Practice

164 BITS Pilani, Deemed to be University under Section 3, UGC Act


PLOTS -3 D

1. Using commands in MATLAB to plot a 3-D figure of the trajectory of a particle


defined by the following set of equations for x,y, and z.Use commands for proper
labelling and title
x=t
y=t*cos(t)
z= e 0.2t
Solution
clear;
clc;
t=0:0.1:10*pi;
x=t;
y=t.*cos(t);
z=exp(0.2*t);
plot3(x,y,z)
title('Plot 3 Dimensional figure');
xlabel('x axis');
ylabel('y axis');
zlabel('z axis');
grid on
165 BITS Pilani, Deemed to be University under Section 3, UGC Act
PLOTS -3 D

x=0:0.1:2;
y=exp(-x)*sin(x);
stem(x,y);
bar(x,y);
title(‘stem and bar Plot’);
xaxis(‘x coordinate’)
yaxis(‘function’);

166 BITS Pilani, Deemed to be University under Section 3, UGC Act

You might also like