You are on page 1of 31

Computer Programming (MATLAB)

Dr. Samir Kale


Lecture 2
BITS Pilani Contact Session: 10.30-12.30
Pilani|Dubai|Goa|Hyderabad
BITS Pilani
Hyderabad Campus

Module: Introduction to MATLAB features


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
3 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)

4 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

5 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

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


Practice Problems and Examples-
Homework

7 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)

8 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

9 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:

10 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

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


Vectors and Matrices

Enter a row in MATLAB : Use ; a=[1,2,3;4,5,6]


Enter a column in MATLAB : Use , a=[1,2,3,4,5,6]

Use : if numbers are in series >> a=1:5

Use : to indicate all rows for example a(:,1) will display all rows of first column

Use : to indicate all columns for example a(1,:) will display all columns of first column

You can use as per convenience , Use of end statement

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


Discussion Points –Contact Session 2

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

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


Discussion Points –Contact Session 2

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

14 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)

15

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
1 • How to show the results from desired
6
source?
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)

17 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.

18 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

1
9

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

20 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

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


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:

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


Discussion Points –Contact Session 2

Problem Solving using MATLAB

Branching Statement
if
if else
Switch

Exercises

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


Discussion Points –Contact Session 2

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.

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


Discussion Points –Contact Session 2

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

25 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

26 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))

27 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)
)

28 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 a356 Mg is 3.00 Composition of a7005 Mg is 14.00
Composition of a2024 Mg is 15.00 Composition of a356 Mn is 0.00 Composition of a7005 Mn is 0.00
Composition of a2024 Mn is 6.00 Composition of a356 Si is 70.00 Composition of a7005 Si is 0.00
Composition of a2024 Si is 0.00 Composition of a356 zn is 0.00 Composition of a7005 zn is 45.00
Composition of a2024 zn is 0.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 a6061 Si is 6.00
Composition of a7075 Mn is 0.00
Composition of a6061 zn is 0.00
Composition of a7075 Si is 0.00
Composition of a7075 zn is 56.00
Composition of a7075 Cuo is 16.00
Composition of a7075 Mg is 25.00
Composition of a7005 Cuo is 0.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

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


Discussion Points –Contact Session 2

Homework Problems

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


Discussion Points –Contact Session 2

% 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

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

You might also like