MAT & C Lab

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

DEPARTMENT OF MECHANICAL ENGG.

C – Programming & MAT Lab

INTRODUCTION TO C – PROGRAMME

C language: It is very popular language because of following reasons


C is structured programming language.
It is considered a high level language because it allows the programmer to solve a problem without
worrying about machine details
Alphabets of ‘C’:- As English language has alphabets such as ‘A’ to Z, C language also has its own
alphabets
CHARACTER: - Any symbol that is used while writing a C –Program is called character or an
alphabet..A character can be a letter, digit or any special symbol
LETTERS:- lower case letter are a,b,c ………..z
Upper case letters are A, B, C……..Z
Digits from 0 to 9
Symbols are : ; semicolon, : colon , , comma, # hash, ( left parentheses ,) right parentheses, { left
braces, } right brace,% percent, = assignment
WHITE SPACES: character such as space, tab (\t), new line (\n), etc also the alphabets of c language
and are called white spaces
C-TOKENS: Tokens is a smallest or basic unit of c programmer. One or more characters are grouped
in sequence to form meaningful words. These meaningful words are tokens. They are classified as
TOKENS
a) Keywords : ex. if , for , while
b) Identifiers : ex. sum, length I, etc
c) Constants : ex.10,a,arya etc
d) Operators : ex. t,-,#,/ etc
e) Special symbols : ex. [ ],{ },( ) etc

KEYWORDS: The tokens which have predefined meaning in c language are called keyword. Since
they are reserved for specified purpose in c language. They are reserved words ex. break, float, long,
integer, switch for, if, void, while
The keywords should not be used as variable names, function names, array names etc. all keywords
should be written in lower case only
IDENTIFIERS: Identifiers are the names given to various programmers such as constants , functions
, names array, etc
Ex. sum, length, I, a, printf, scanf,

ARYABHARATI POLYTECHNIC, TUMKUR. 1


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab
CONSTANTS: A Constant is a data. Item will not change during the execution of a programme. It
cannot be modified in programme
Ex. I) numeric constants - 1) Integer
a) decimal
b) octal
2) floating constants
a) fractional
II) Character constants eg: a,9,etc
III) string constant eg: arya, etc

INTEGER : An integer is a whole number with out any fraction part

FLOATING NUMBER :The numbers with fractions eg: 99.99,58.25 etc

INT: An int is a key word which is used to define integers in c language. Using int keywords c
supports three different sizes
1) Short int
2) Int Here short and long int are type qualifiers
3) Long int

FLOAT: Afloat is akey word which is used to define floating point numbers in c language eg: 3.45,
22.35

VOID: Avoid is a empty data type since there is no value is associated with this data type it does not
occupy any space in the memory

ARYABHARATI POLYTECHNIC, TUMKUR. 2


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab
C PROGRAMMING STRUCTURE:

1) PRE PROCESSOR DIRECTIVES :These are called pre compilers directives . thr pre
processor accept the source programme and prepare the source programme for compilation. The
pre processor stamensts stars with symbol #. The normal preprocessor used in all programme
include . this instruct the pre processor to include the specified file contents in the beginning of
the programme.
eg: # include < stdio.h>
2) GLOBAL DECLARATIONS :These are the variables that are define immediately after pre
processor or directives . these variables are visible to all parts of the programme hence the name
global variables
3) MAIN( ): Every programme should have main ( )there should be only one function by name
main( ) this is the first function to be executed always .the function main may call other functions
. the statement enclosed with in left and right brace is a called body of the function.
the main function is divided in to two parts
1)Declaration section
2) Executable section

ARYABHARATI POLYTECHNIC, TUMKUR. 3


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

1) Write a c programme to check whether a number is prime or not

#include<stdio.h>
#include<conio.h>
void main()
{
int flag=0,n,i;
clrscr();
printf(" Enter the Number\n");
scanf("%d",&n);
for(i=2; i<n; i++)
if (n%i= =0)
{
flag=1;
}
if(flag==0)
printf("\n\n %d is a prime Number\n",n);
else
printf("\n\n %d is a not prime Number\n",n);
getch();
}

Output:

ARYABHARATI POLYTECHNIC, TUMKUR. 4


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

2) Write a c programme to find Sum and average of 3 real numbers

#include<stdio.h>

#include<conio.h>

main()

float a, b, c, sum, avg;

clrscr();

printf("Enter value of three numbers: ");

scanf("%f %f %f", &a, &b, &c);

sum = a + b + c;

avg = sum / 3;

printf("The Sum of 3 numbers %.f \n", sum);

printf("The Average of 3 numbers %f\n", avg);

getch();

OUTPUT:

ARYABHARATI POLYTECHNIC, TUMKUR. 5


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

3) Write a c programme To find Largest of 3 numbers using if


statements

#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c;
clrscr( );
printf("enter the values of a,b,c");
scanf("%d,%d,%d",&a,&b,&c);
if(a>b&&a>c)
printf("\n\n %d is greater \n",a);
else
if (b>a&&b>c)
printf("\n\n %d is greater \n",b);
else
printf("\n\n %d is greater \n",c);
getch();
}

OUT PUT :

ARYABHARATI POLYTECHNIC, TUMKUR. 6


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

4) Write a program to find out whether it is an odd number or even number.

#include<stdio.h>
#include<conio.h>
main()
{
int n;
clrscr();
printf ("Enter the number\n");
scanf ("%d",&n);
if (n%2==0)
{
printf ("The entered number is EVEN.\n",n);
}
else
{
printf ("The entered number is ODD.\n",n);
getch();
}
}

OUTPUT:

ARYABHARATI POLYTECHNIC, TUMKUR. 7


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

5) Write a program to find sum of the digits of a given number

#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );

Long n;
intsum=0,digit;
printf("Enter any number\n");
scanf("%ld",&n);
while(n>0)
{
digit=n%10;
n=n/10;

sum=sum+digit;

}
printf("Sum of digits of a number %d\n", sum);
getch();
}

OUTPUT:

ARYABHARATI POLYTECHNIC, TUMKUR. 8


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

6) Write a program to swap two numbers using user defined functions

#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b;
clrscr()
printf(“enter the value of a and b \n”);
scanf(“%d%d”,&a,&b);
printf(“Before swapping the valve of a is %d & b is %d\n”, a,b);
a=a+b;
b=a-b;
a=a-b;
printf(“after swapping the valve of a is %d & b is %d\n”, a,b);
getch();
}

OUTPUT:

ARYABHARATI POLYTECHNIC, TUMKUR. 9


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

7) Write a program to find to find the addition of two matrices


#include<stdio.h>
#include<conio.h>
void main( )
{
int a[10][10],b[10][10],c[10][10],i,j,row,col,
clrscr();
printf("Enter the number of rows and columns\n");
scanf("%d%d",&row,&col);
printf("Enter the elements of array a\n");
for(i=0;i<row;i++)
for(j=0;j<col;j++)
scanf("%d",&a[i][j]);
printf("Enter the elements of array b\n");
for(i=0;i<row;i++)
for(j=0;j<col;j++)
scanf("%d",&b[i][j]);
printf("Enter the elements matrix a is \n\n”);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf("\t%d”,a[i][j]);
printf(“\n”);
}
Printf(“\n elements of matrix b\n\n”);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf("\t%d”,b[i][j]);
printf(“\n”);
}
for(i=0;i<row;i++)
for(j=0;j<col;j++)
c[i][j]=a[i][j]+b[i][j];
printf(“matrix addition is \n\n”);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf("\t%d”,c[i][j]);
printf(“\n”);
}
getch( );
}

OUTPUT:

ARYABHARATI POLYTECHNIC, TUMKUR. 10


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

8) Write a program to find to find the subtraction of two matrices


#include<stdio.h>
#include<conio.h>
void main( )
{
int a[10][10],b[10][10],c[10][10],i,j,row,col,
clrscr();
printf("Enter the number of rows and columns\n");
scanf("%d%d",&row,&col);
printf("Enter the elements of array a\n");
for(i=0;i<row;i++)
for(j=0;j<col;j++)
scanf("%d",&a[i][j]);
printf("Enter the elements of array b\n");
for(i=0;i<row;i++)
for(j=0;j<col;j++)
scanf("%d",&b[i][j]);
printf("Enter the elements matrix a is \n\n”);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf("\t%d”,a[i][j]);
printf(“\n”);
}
Printf(“\n elements of matrix b\n\n”);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf("\t%d”,b[i][j]);
printf(“\n”);
}
for(i=0;i<row;i++)
for(j=0;j<col;j++)
c[i][j]=a[i][j] - b[i][j];
printf(“matrix subtraction is \n\n”);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf("\t%d”,c[i][j]);
printf(“\n”);
}
getch( );
}

OUTPUT:

ARYABHARATI POLYTECHNIC, TUMKUR. 11


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

9) Write a c program to arrange n-numbers in ascending using Bubble sort


technique
#include<stdio.h>
#include<conio.h>
main()
{
Int num[10];
Int loop,i;
Int last=10;
Int exchg;
Int temp;
clrscr();
printf(“enter 10 elements of the array as integer number\n”);
for(i=0;i<10;++i)
scanf(“%d”,&num[i]);
for(loop=0;loop<9;++loop)
{
exchg=0;
for(i=0;i<(last-1);i++)
if(num[i]>num[i+1])
{
temp=num[i];
num[i]=num[i+1];
num[i+1]=temp;
exchg=exchg+1;
}
If(exchg==0)
break;
else
last=(last-1);
}
printf(“numbers in ascending order are as follows\n”);
for(i=0;i<10;++i)
printf(“%d \n”,num[i]);
getch();
}

OUTPUT:

ARYABHARATI POLYTECHNIC, TUMKUR. 12


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

10) Write a c program to find multiplication of two matrices


#include<stdio.h>
#include<conio.h>
main()
{
Int a[10][10],b[10][10],mul[10][10],i,j,k,r,c,r1,c1;
clrscr();
printf(“enter the size of first matrix\n”);
scanf(“%d%d”,&r,&c);
printf(“enter the size of second matrix\n”);
scanf(“%d%d”,&r1,&c1);
if(c!=r1)
{
Printf(“the multiplication can’t be done\n”);
getch();
}
Printf(“enter the elements of matrix a \n”);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf(“%d”,&a[i][j]);
printf(“enter the elements of matrix b \n”);
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
scanf(“%d”,&b[i][j]);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
mul[i][j]=0;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
for(k=0;k<c;k++)
{
mul[i][j]=mul[i][j]+a[i][k]*b[k][j];
}
Printf(“the multiplication of two matrix=\n”);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
printf(“\t%d”,mul[i][j]);
printf(“\n”);
}
getch();
}

OUTPUT:

ARYABHARATI POLYTECHNIC, TUMKUR. 13


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

11) Write a c program finding the roots of the quadratic equation using switch-
statement
#include<stdio.h>
#include<conio.h>
#include<math.h>
main( )
{
float a,b,c,d,x1,x2;
clrscr();
printf(“enter the values of a,b,c\n”);
scanf(“%f%f%f”,&a,&b,&c);
d=b*b-4*a*c;
if(d>0)
{
X1=(-b+sqrt(d))/(2*a);
X2=(-b-sqrt(d))/(2*a);
Printf(“the roots are distict\n”);
Printf(“x1=%f\nx2=%f\n”,x1,x2);
If(d==0)
x1=x2=-b/(2*a);
printf(“the roots are equal\n”);
printf(“x1=%f\nx^2=%f\n”,x1,x2);
}
else
{
x1=-b/(2*a);
x2=sqrt(fabs(d))/(2*a);
printf(“the roots are complex\n”);
printf(“first root=%f+i%f\n”,x1,x2);
printf(“second root=%f-i%f\n”,x1,x2);
}
getch();
}

OUTPUT:

ARYABHARATI POLYTECHNIC, TUMKUR. 14


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

MAT LAB

ARYABHARATI POLYTECHNIC, TUMKUR. 15


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

1.0 INTRODUCTION

MATLAB is a powerful language for technical computing. The name MATLAB stands for
Matrix Laboratory, because its basic data element is a matrix (array). MATLAB can be used for math
computations, modeling and simulations, data analysis and processing, visualization and graphics, and
algorithm development. MATLAB is widely used in universities and colleges in introductory and
advanced courses in mathematics, science, and especially engineering. In industry the software is used
in research, development, and design. The standard MATLAB program has tools (functions) that can
be used to solve common problems. In addition, MATLAB has optional toolboxes that are collections
of specialized programs designed to solve specific types of problems. Examples include toolboxes for
signal processing, symbolic calculations, and control systems.

1.1 Software and Hardware


The MATLAB program, like most other software, is continually being developed and new
versions are released frequently. This book covers MATLAB Version 7.11, Release 2010b. It should
be emphasized, however, that the book covers the basics of MATLAB, which do not change much
from version to version. The book covers the use of MATLAB on computers that use the Windows
operating system. Everything is essentially the same when MATLAB is used on other machines. The
user is referred to the documentation of MATLAB for details on using MATLAB on other operating
systems. It is assumed that the software is installed on the computer, and the user has basic knowledge
of operating the computer.

ARYABHARATI POLYTECHNIC, TUMKUR. 16


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

Chapter – 2
Starting with MATLAB
It is assumed that the software is installed on the computer, and that the user can start the
program. Once the program starts, the MATLAB desktop window opens (Figure 1-1). The window
contains four smaller windows: the Command Window, the Current Folder Window, the Workspace
Window, and the Command History Window. This is the default view that shows four of the various
windows of MATLAB. A list of several windows and their purpose is given in Table 1-1. The Start
button on the lower left side can be used to access MATLAB tools and features. Four of the
windows—the Command Window, the Figure Window, the Editor Window, and the Help Window—
are used extensively throughout the book and are briefly described on the following pages. More
detailed descriptions are Included in the chapters where they are used. The Command History
Window, Current Folder Window, and the Workspace Window are described in Sections 1.2, 1.8.4,
and 4.1, respectively.

2.1 Command Window: The Command Window is MATLAB’s main window and opens when
MATLAB is started. It is convenient to have the Command Window as the only visible window, and
this can be done by either closing all the other windows (click on the x at the top right-hand side of the
window you want to close) or by first selecting the Desktop Layout in the Desktop menu, and then
selecting Command Window Only from the submenu that opens. Working in the Command Window

2.2 Figure Window: The Figure Window opens automatically when graphics commands are
executed, and contains graphs created by these command

ARYABHARATI POLYTECHNIC, TUMKUR. 17


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab
2.3 Editor Window: The Editor Window is used for writing and editing programs. This window is
opened from the File menu. An example of an Editor Window is shown in Figure 1-3. More details on
the Editor Window are given in Section 1.8.2, where it is used for writing script files, and in Chapter
7, where it is used to write function files.

2.4 Help Window: The Help Window contains help information. This window can be opened from the
Help menu in the toolbar of any MATLAB window. The Help Window is interactive and can be used
to obtain information on any feature of MATLAB. Figure 1-4 shows an open Help Window.
Table 1.1
Window Purpose
Command Window Main window, enters variables,
runs
programs.
Figure Window Contains output from graphic
commands
Editor Window Creates and debugs script and
function files.
Help Window Provides help information.
Command History Logs commands entered in the
Window Command Window.
Workspace Window Provides information about the
variables that are used.
Current Folder Shows the files in the current
Window folder

ARYABHARATI POLYTECHNIC, TUMKUR. 18


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab
2.2 WORKING IN THE COMMAND WINDOW
The Command Window is MATLAB’s main window and can be used for executing commands,
opening other windows, running programs written by the user, and managing the software. An
example of the Command Window, with several simple commands that will be explained later in this
chapter, is shown in Figure 1-5. Notes for working in the Command Window:

1. To type a command the cursor must be placed next to the command prompt ( >> ).
2. Once a command is typed and the Enter key is pressed, the command is executed.
3. However, only the last command is executed. Everything executed previously
4. (That might be still displayed) is unchanged.
5. Several commands can be typed in the same line. This is done by typing a comma
6. between the commands. When the Enter key is pressed the commands are executed in order from
left to right.
7. It is not possible to go back to a previous line that is displayed in the Command
8. Window, make a correction, and then re-execute the command.
9. A previously typed command can be recalled to the command prompt with the up arrow key (
). When the command is displayed at the command prompt, it can be modified if needed and then
executed. The down-arrow key ( ) can be used to move down the list of previously typed
commands.
10. If a command is too long to fit in one line, it can be continued to the next line by typing three
periods … (called an ellipsis) and pressing the Enter key. The continuation of the command is
then typed in the new line. The command can continue line after line up to a total of 4,096
characters.
 The semicolon ( ; ):
When a command is typed in the Command Window and the Enter key is pressed, the command
is executed. Any output that the command generates is displayed in the Command Window. If a
semicolon ( ; ) is typed at the end of a command the output of the command is not displayed. Typing a
semicolon is useful when the result is obvious or known, or when the output is very large. If several
commands are typed in the same line, the output from any of the commands will not be displayed if a
semicolon is typed between the commands instead of a comma.
 Typing %:
When the symbol % (percent) is typed at the beginning of a line, the line is designated as a
comment. This means that when the Enter key is pressed the line is not executed. The % character
followed by text (comment) can also be typed after a command (in the same line). This has no effect

ARYABHARATI POLYTECHNIC, TUMKUR. 19


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab
on the execution of the command. Usually there is no need for comments in the Command Window.
Comments, however, are frequently used in a program to add descriptions or to explain the program

 The clc command:


The clc command (type clc and press Enter) clears the Command Window. After working in the
Command Window for a while, the display may become very long. Once the clc command is executed
a clear window is displayed. The command does not change anything that was done before. For
example, if some variables were defined previously they still exist and can be used. The up-arrow key
can also be used to recall commands that were typed before.

 The Command History Window:


The Command History Window lists the commands that have been entered in the Command
Window. This includes commands from previous sessions. A command in the Command History
Window can be used again in the Command Window. By double-clicking on the command, the
comman is reentered in the Command Window and executed. It is also possible to drag the command
to the Command Window, make changes if needed, and then execute it. The list in the Command
History Window can be cleared by selecting the lines to be deleted and then selecting Delete Selection
from the Edit menu (or right-click the mouse
when the lines are selected and then choose Delete Selection in the menu that opens).

ARITHMETIC OPERATIONS WITH SCALARS


In this chapter we discuss only arithmetic operations with scalars, which are numbers. As will be
explained later in the chapter, numbers can be used in arithmetic calculations directly (as with a
calculator) or they can be assigned to variables, which can subsequently be used in calculations. The
symbols of arithmetic operations are:
Operation Symbol Example
Addition + 5+3
Subtraction – 5–3
Multiplication * 5*3
Right division / 5/3
Left division \ 5\3=3/5
Exponentiation ^ 5 ^ 3 (means 53 = 125)

ARYABHARATI POLYTECHNIC, TUMKUR. 20


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

Order of Precedence
MATLAB executes the calculations according to the order of precedence displayed below. This order
is the same as used in most calculators.
Precedence Mathematical Operation
First Parentheses. For nested parentheses, the innermost are executed first.
Second Exponentiation.
Third Multiplication, division (equal precedence).
Fourth Addition and subtraction
In an expression that has several operations; higher-precedence operations are executed before
lower-precedence operations. If two or more operations have the same precedence, the expression is
executed from left to right. As illustrated in the next section, parentheses can be used to change the
order of calculations.
Using MATLAB as a Calculator
The simplest way to use MATLAB is as a calculator. This is done in the Command Window
by typing a mathematical expression and pressing the Enter key. MATLAB calculates the expression
and responds by displaying ans. = and the numerical result of the expression in the next line
Using MATLAB as a calculator.
>> 7+8/2 Type and press Enter.
ans = 8/2 is executed first.
11

>> (7+8)/2 Type and press Enter.


ans = 7+8 is executed first.
7.5000

>> 4+5/3+2 5/3 is executed first


ans =
7.6667

>> 5^3/2 . 5^3 is executed first ,


/2 is executed next.
ans =
62.5000

>> 27^(1/3)+32^0.2 1/3 is executed first, 27^(1/3) and 32^0.2 are


executed next, and + is executed last
ans =
5

>> 27^1/3+32^0.2 27^1 and 32^0.2 are executed first, /3 is executed


next, and + is executed last.
ans =
11

ARYABHARATI POLYTECHNIC, TUMKUR. 21


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

Elementary math functions


Function Description Example
sqrt(x) Square root. >> sqrt(81)
ans =9
nthroot(x,n) Real nth root of a real >> nthroot(80,5)
number x. ans =
(If x is negative n must 2.4022
be anodd integer.)
exp(x) Exponential . (ex) >> exp(5)
ans =
148.4132
abs(x) Absolute value. >> abs(-24)
ans =24
log(x) Natural logarithm. >> log(1000)
Base e logarithm (ln). ans =6.9078
log10(x) Base 10 logarithm. >> log10(1000)
ans =3.0000
Trigonometric math functions
Function Description Example
sin(x) Sine of angle x (x in radians). >> sin(pi/6)
sind(x) Sine of angle x (x in degrees). ans =0.5000

cos(x) Cosine of angle x (x in radians). >> cosd(30)


cosd(x) Cosine of angle x (x in degrees). ans =0.8660

tan(x) Tangent of angle x (x in radians). >> tan(pi/6)


tand(x) Tangent of angle x (x in degrees). ans =0.5774

cot(x) Cotangent of angle x (x in radians). >> cotd(30)


cotd(x) Cotangent of angle x (x in degrees). ans =1.7321

ARYABHARATI POLYTECHNIC, TUMKUR. 22


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

Problem no 1

Trigonometric identity
A trigonometric identity is given by:
cosx2 = tanx + sinx
2tanx
Verify that the identity is correct by calculating each side of the equation, substituting
. X= π/5
Solution
The problem is solved by typing the following commands in the Command Window.
>> x=pi/5;
>> LHS=cos(x/2)^2
LHS = 0.9045
>> RHS= (tan(x) +sin(x))/ (2*tan(x))
RHS = 0.9045

The following problems can be solved by writing commands in the Command


Window, or by writing a program in a script file and then executing the file.

1.1) 2x4 – 6x3 + 14.8x2 + 9.1 for (x=2.34)


1.2) sin4x = 4sinx cosx – 8 sin3x cosx for (x= /9)
1.3) cos2x = 1- tan2 x for (x= /9)
1 + tan2x

ARYABHARATI POLYTECHNIC, TUMKUR. 23


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab
Equivalent force system (addition of vectors)

Problem no 2: Three forces are applied to a bracket as shown. Determine the total (equivalent)
force applied to the bracket.

Solution F3=700N F2=500N


143O
300
20O

F1=400N

The total (equivalent) force applied on the bracket is obtained by adding the
forces that are acting on the bracket. The MATLAB solution below follows three steps:
1. Write each force as a vector with two elements, where the first element is the x component of
the vector and the second element is the y component.
2. Determine the vector form of the equivalent force by adding the vectors.
3. Determine the magnitude and direction of the equivalent force.

The problem is solved in the following script file.

f1=400; f2=500; f3=700 Define variables with the


magnitude of each vector.
Th1=-20; Th2=30; Th3=143; Define variables with the angle of
each vector
F1=f1*[cosd(Th1) Sind(Th1)]
F2=f2*[cosd(Th2) Sind(Th2)] Define the three vectors
F3=f3*[cosd(Th3) Sind(Th3)]

Ftot=F1+F2+F3 Calculate the total force vector.

FtotM=sqrt(Ftot(1)^2+Ftot(2)^2) Calculate the magnitude of


the total force vector.
Th=atand(Ftot(2)/Ftot(1)) Calculate the angle of the total
force vector

ARYABHARATI POLYTECHNIC, TUMKUR. 24


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

Friction experiment (element-by-element calculations)

Problem no 3: The co-efficient of friction mu can be determined in an experiment by measuring the


force F required to move a mass m. when F is measured and m is known the coefficient of friction can
be calculated by mu=F/mg (g=9.81 m/sec2) results from measuring F in six tests are given in the table
below. Determine the coefficient of friction in each test, and average from all tests

F
mm
m Friction
Test # 1 2 3 4 5 6
Mass m-kg 2 4 5 10 20 50
Force F -N 12.5 23.5 30 61 117 294

The coefficient of friction, μ, can be determined in an experiment by measuring the force F required to
move a mass m. When F is measured and m is known, the coefficient of friction can be calculated by:
μ = F ⁄ (mg) (g = 9.81 m/s2).

Results from measuring F in six tests are given in the table above Determine the coefficient of friction
in each test, and the average from all tests

Solution
A solution using MATLAB commands in the Command Window is shown below.
>> m=[2 4 5 10 20 50]; Enter the values of m in a vector.

>> F=[12.5 23.5 30 61 117 294]; Enter the values of F in a vector.


>> mu=F./(m*9.81) A value for mu is calculated for
each test, using element-by- element calculations.

mu = 0.6371 0.5989 0.6116 0.6218 0.5963 0.5994

>> mu_ave=mean(mu) The average of the elements in the vector


mu
is determined by using the function mean.

mu_ave =0.6109

ARYABHARATI POLYTECHNIC, TUMKUR. 25


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

USING SCRIPT FILES AND MANAGING DATA


(HEIGHT AND SURFACE AREA OF A SILO)

Problem no 3: A cylindrical silo with radius r has a spherical cap roof with radius R. the height of
the cylindrical portion is H. write a program in a script file that determines the height H for given
values of r, R and the volume V. In addition, the program also calculates the surface area of the silo.
Use the program to calculate the height and surface area of a silo with r=30 m , R=45m and volume of
120000 cubic metre.. assign values for r,R and V in the command window.

clc
r = input('Enter the radius of Cylindrical Silo = ');
R = input('Enter the Radius of Sperical Cap = ');
V = input('Enter the Volume of Cylindrical Silo = ');
th = asin(r/R);
h = R-R*cos(th);
vcp = pi*h^2*(3*R-h)/3;
H = (v-vcp)/(pi*r^2);
s = 2*pi*(r*H+R*h);
fprintf ('The Height of Cylindrical Silo H= %f \n', H);
fprintf ('The Surface Area of Cylindrical Silo s= %f \n', s);

OUTPUT: <Type file name in command window>


Enter the radius of Cylindrical Silo = 30
Enter the Radius of Sperical Cap = 45
Enter the Volume of Cylindrical Silo = 200000
The Height of Cylindrical Silo H= 64.727400
The Surface Area of Cylindrical Silo s= 15440.777753

ARYABHARATI POLYTECHNIC, TUMKUR. 26


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

Two-Dimensional Plots (Piston-crank mechanism)

Problem no 4: The piston-connecting rod-crank mechanism is used in many engineering


applications. In the mechanism shown in the following fig. The crank is rotating at constant speed
of 500 rpm. Calculate and plot the position, velocity and acceleration of the piston for one revolution
of the crank. Make the three plots on the same page. Set theta=0 when t=0.

Calculate and plot the position, velocity, and acceleration of the piston for one
revolution of the crank.

clc
rpm = input('Enter the RPM = ');
r = input('Enter the Length of Rod = ');
c = input('Enter the Length of Crank = ');
rad = rpm*2*pi/60;
tr = 2*pi/rad;
t = linspace(0, tr, 200);
th = rad*t; f = c^2-r^2*sin(th).^2;
x = r*cos(th)+sqrt(f);
dx = -r*rad*sin(th)-(r^2*rad*sin(2*th))./(2*sqrt(f));
ddx=-r*rad^2*cos(th)- (4*r^2*rad^2*cos(2*th).*f+(r^2*sin(2*th)*rad).^2)./(4*f.^1.5); subplot(3,1,1)

plot(t,x)
grid
xlabel('Time----->')
ylabel('Position----->')
subplot(3,1,2)
plot(t,dx)
grid

ARYABHARATI POLYTECHNIC, TUMKUR. 27


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab
xlabel('Time----->')
ylabel('Velocity----->')
subplot(3,1,3)
plot(t,ddx)
grid
xlabel('Time----->')
ylabel('Acceleration----->')

OUTPUT: <Type file name in command window>


Enter the RPM = 500
Enter the Length of Rod = 0.12
Enter the Length of Crank = 0.25

ARYABHARATI POLYTECHNIC, TUMKUR. 28


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab
(6). Create a function file that calculates the trajectory of a
projectile. The inputs to the function are the initial velocity
and the angle at which the projectile is fired. The outputs
from the function are the maximum height and distance. In
addition, the function generates a plot of the trajectory. Use
the function to calculate the trajectory of a projectile that is
fired at a velocity of 230 m/sec at an angle of 39 deg.

Solution:

function[hmax,dmax] = prog6_me(v,th)

g=9.81;

vx=v*cos(th*pi/180);

vy=v*sin(th*pi/180);

thmax=vy/g;

hmax=vy^2/(2*g);

tt=2*thmax;

dmax=vx*tt;

tplot=linspace(0,tt,200);

x=vx*tplot;

y=vy*tplot-0.5*g*tplot.^2;

plot(x,y)

OUTPUT:

>> [h , d] = prog6_me(230,39)

h = 1.0678e+003

d = 5.2746e+003

ARYABHARATI POLYTECHNIC, TUMKUR. 29


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab
(7).The outside dimensions of a rectangular box (top open) made of aluminium is 24x12x4
inches. The wall thickness of the bottom and the sides is x. derive an expression that relates the
weight of the box and the wall thickness x. determine the thickness x for the box that weighs 15
lbs. The specific weight of the aluminium is 0.101 lb/cubic inch.

Solution:

clc
w = input('Enter the Weight of Aluminum Rectangular box w= ');
sp = input('Enter the Specific Weight of Aluminum box sp= ');
v = w/sp; a = [-2 24];
b = [-2 12];
c = [-1 4];
temp = conv(c,conv(a,b));
poly = [0 0 0 (v-24*12*4)] + temp
x = roots (poly)
OUTPUT: <Type file name in command window>
Enter the Weight of Aluminum Rectangular box w= 15
Enter the Specific Weight of Aluminum box sp= 0.101
poly = -4.0000 88.0000 -576.0000 148.5149 The polynomial is:
– 4x3 + 88x2 – 576x + 148.515.
x=
10.8656 + 4.4831i The polynomial has one real root, x = 0.2687
in.,which is the thickness of the aluminum wall.
10.8656 - 4.4831i
0.2687

ARYABHARATI POLYTECHNIC, TUMKUR. 30


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

(8) Viscosity mu is property of gases and fluids that characterises their resistance to flow. For
most materials viscosity is highly sensitive to temperature. Below is a table that gives the
viscosity of SAE 10w oil at different temperatures. Determine an equation that can be fitted to
the data.

T(Oc)
-20 0 20 40 60 80 100 120

μ (Ns/m2)
(x10-5)
4.000 0.38 0.095 0.032 0.015 0.0078 0.0045 0.0032
SOLUTION:

clc
t=[-20 0 20 40 60 80 100 120];
u=[4 0.38 0.095 0.032 0.015 0.0078 0.0045 0.0032];
tk=t+273;
p=polyfit(tk,log(u),2)
tp=273+[-20:120];
mp=exp(p(1)*tp.^2+p(2)*tp+p(3));
semilogy(tk,u,'o',tp,mp)
xlabel('Temperature (K)----->')
ylabel('Viscosity----->')

OUTPUT:
<Type file name in command window>
p = 0.0003 -0.2685 47.1673
>>

ARYABHARATI POLYTECHNIC, TUMKUR. 31


DEPARTMENT OF MECHANICAL ENGG. C – Programming & MAT Lab

(9) A safety bumper is placed at the end of a race track to stop out of control cars. The bumper
is designed such that the force that the bumper applies to the car is a function of the velocity v
and displacement x of the front edge of the bumper according to the equation. F=Kv3(x+1)3
where K=30 s-kg/m5 is a constant. A car with a mass m of 1500 kg hits the bumper at a speed of
90 km/hr. Determine and plot the velocity of the car as a function of its position for 0≤x≤3 m.

clc % main program


global k m
k = 30; % Constant
m = 1500; % Mass of car
v = 90; % Velocity of car
range = [0:0.2:3];
vmps = v*1000/3600;
[x v] = ode45('bumper',range,vmps)
plot (x,v)
xlabel (‘ x (m)-----> ‘)
ylabel (‘ Velocity (m/s) ----->’)

→ function dvdx = bumper(x,v) % Sub program file name must be bumper.m


global k m
dvdx = -(k*v^2*(x+1)^3)/m;

OUTPUT:
<Type main program file name in command window>
>> x = v=
0.0000 25.0000
0.2000 22.0420
0.4000 18.4478
0.6000 14.7561
0.8000 11.4302
1.0000 8.6954
1.2000 6.5733
1.4000 4.9793
1.6000 3.7960
1.8000 2.9220
2.0000 2.2737
2.2000 1.7886
2.4000 1.4226
2.6000 1.1435
2.8000 0.9283
3.0000 0.7607

ARYABHARATI POLYTECHNIC, TUMKUR. 32

You might also like