BITS Pilani: Computer Programming (MATLAB) Dr. Samir Kale Revision Class-01/03/2019
BITS Pilani: Computer Programming (MATLAB) Dr. Samir Kale Revision Class-01/03/2019
BITS Pilani: Computer Programming (MATLAB) Dr. Samir Kale Revision Class-01/03/2019
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
2. Applied Fields:
Operator Purpose
\ Left-division operator.
/ Right-division operator.
Operator Purpose
: Colon; generates regularly spaced elements and represents an entire row or column.
. Decimal point.
= Assignment operator.
In MATLAB, and many other programming languages, operations are performed in the
following order:
• expressions in brackets: ( ) ;
• powers: ^ ;
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
>> 8^(2/3)
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
#include <stdio.h>
int main()
{
double n1, n2, n3;
data = [a,b,c];
}
largest = data(1);
for i = 1:length(data) I
largest = data(i);
end
end
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
2) Change the Current directory to mynewdir. Then open an Edit Window and add the
following lines
t=-2*pi:pi/10:2*pi
% Calculate |sin(t)|
x=abs(sin(t));
% Plot result
plot(t,x)
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
• 3456
• 1.0000 1.5000 2.0000 2.5000 3.0000
• 5432
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:
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
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
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
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
• Matrices can be of different sizes, either square matrices of size NxN or rectangular NxM
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=
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
>> 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
Colon Operator
First:incr:last
>> x=1:2:10
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
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.
• M = max(A,[ ],2)
• M = 1.7000 1.9900
(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
a = 20;
b = 10;
c = 30;
data = [a,b,c];
largest = data(1);
for i = 1:length(data)
largest = data(i);
end
end
MATLAB-First Program
#include <stdio.h>
int main()
{
double n1, n2, n3;
data = [a,b,c];
}
largest = data(1);
for i = 1:length(data) I
largest = data(i);
end
end
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
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
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
• 3456
• 1.0000 1.5000 2.0000 2.5000 3.0000
• 5432
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(' ')
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.
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))
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)))
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
2) Change the Current directory to mynewdir. Then open an Edit Window and add the
following lines
t=-2*pi:pi/10:2*pi
% Calculate |sin(t)|
x=abs(sin(t));
% Plot result
plot(t,x)
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
Display Options
temp=78;
>> disp(temp);
disp(’degrees F’)
output
78
degrees F
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)
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?
%Matlab
radius = 5
area = pi * (radius^2)
>> areacircle
radius =
5
area =
78.5398
>>type areacircle
radius = 5
area = pi * (radius^2)
input
disp
fprintf
printing vectors matrices with disp/fprintf
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
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
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:
Branching Statement
if
if else
Switch
Exercises
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.
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
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
)
63 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
Homework Problems
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)
Switch <switch_expression>
otherwise <statements>
end
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
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
Syntax of If Statements
for a = 10:20
fprintf('value of a: %d\n', a);
End
for m = 1:j
for n = 1:k
<statements>; end
End
while <expression1>
while <expression2>
<statements> end
end
for i=2:100
for j=2:100
if(~mod(i,j))
end
end
end
end
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).
7+6
format short , long, bank
Addition
Multiplication
conv(x,y)
deconv(x,y)
kron (x,y)
cumsum(x)
cumprod(x)
max(x)
mean(x)
transpose(x)
std(x)
fliplr(x)
flipdim(x)
size(x)
var(x)
find(x>4)
Branching Statement
if
if else
Switch
Exercises
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)
Switch <switch_expression>
otherwise <statements>
end
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
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
Syntax of If Statements
for a = 10:20
fprintf('value of a: %d\n', a);
End
for m = 1:j
for n = 1:k
<statements>; end
End
while <expression1>
while <expression2>
<statements> end
end
for i=2:100
for j=2:100
if(~mod(i,j))
end
end
end
end
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).
Branching Statement
if
if else
Switch
Exercises
Branching Statement
if
if else
Switch
Exercises
-4x+3y+z=-18.2
5x+6y -2z=-48.8
2x-5y+4.5z=92.5
4.
-4x+3y+z=-18.2
5x+6y -2z=-48.8
2x-5y+4.5z=92.5
Solve yourself
x = 100;
y = -10;
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
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
Syntax of If Statements
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).
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
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)
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)
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')
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
[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R; f
figure
mesh(Z)
[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R; f
igure
mesh(Z)
[X,Y] = meshgrid(1:0.5:10,1:20);
Z = sin(X) + cos(Y);
surf(X,Y,Z)
Reusable Code
137 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Format
% 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)
>> computetraj
causes the instructions (ie., the MATLAB commands) in the file to be run.
Subfunctions (4)
Nested functions (4)
Anonymous functions (4)
Function_handles (4)
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.
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.
function volume =
volume_sphere(radius)
volume=4/3*pi.*(radius^3);
end
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
comments
dp = sum(v.*w);
• >>
• >> 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
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
% 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 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;
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
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;
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.
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].
a= 1.3;
b = .2;
c = 30;
parabola = @(x) a*x.^2 + b*x + c;
abc
Clear
x = 1;
y = parabola(x)
x = 1;
y = 10;
z = myfunction(x,y)
g = inline('t^2')
g=
g(t) = t^2
f = inline('3*sin(2*x.^2)')
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’);