0% found this document useful (0 votes)
71 views12 pages

Experiment 1 - Fundamental Concepts

This document provides an introduction and overview of MATLAB. It discusses how to run MATLAB, work with the command window, define scalar variables and matrices, and address elements in matrices. Key points include: - MATLAB is a numerical computing environment for working with matrices and can perform mathematical operations and visualize data. - The command window is used to enter commands and view outputs. Variables can be defined using assignment operators and matrices created using brackets and semicolons. - MATLAB has built-in functions, variables, and operators to perform common numeric, scientific, and engineering tasks like linear algebra and plotting. Matrices allow efficient storage and manipulation of multi-dimensional data.

Uploaded by

Shahab Hamid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views12 pages

Experiment 1 - Fundamental Concepts

This document provides an introduction and overview of MATLAB. It discusses how to run MATLAB, work with the command window, define scalar variables and matrices, and address elements in matrices. Key points include: - MATLAB is a numerical computing environment for working with matrices and can perform mathematical operations and visualize data. - The command window is used to enter commands and view outputs. Variables can be defined using assignment operators and matrices created using brackets and semicolons. - MATLAB has built-in functions, variables, and operators to perform common numeric, scientific, and engineering tasks like linear algebra and plotting. Matrices allow efficient storage and manipulation of multi-dimensional data.

Uploaded by

Shahab Hamid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

EXPERIMENT 1 – FUNDAMENTAL CONCEPTS

Objective
 Introduction of MATLAB
 Understand how programs are written in MATLAB
 Understand the MATLAB windows, working with basic commands, Elementary built in functions, Variable
declaration and Rules for variables
Time Required : 3 hrs
Programming Language : MATLAB
Software Required : MATLAB
Hardware Required : NIL

Introduction
MATLAB is stand for MATrix LABoratory. It is a mathematical package based on matrices and consists of
extensive library of numerical routines.
 All Data stored in the form of a matrix
 Case-sensitive
 The basic data type is matrix (normally with 16 decimals precision)
 Possible to handle complex numbers
 High-Level programming language and Matrix based computing environment
 Visualization of data as advanced graphics two and three dimensional
How to run MATLAB
From Start Menu -> Select Programs ->Select MATLAB 7.1

MATLAB Prompt
Tells that MATLAB
is ready for your
command

Working with command window


 Type command in the front of command prompt (>>)
 Press Enter key, the command is executed.
 Several commands can be typed in the same line by separating by comma.
 Previously typed command can be recalled by up-arrow key and down-arrow key can be used to move
down the previously typed commands.
 If the command is too long to fit in one line, it can be continued to the next line by typing three dots …
(called an ellipsis)

1 Numerical Methods – Fundamental Concepts


Command window

>> 39*4.4+5

ans =
176.6000 The MATLAB command
Command window

The result.

The Semicolon (;)


When command is executed the very next will display the output of the command. If a semicolon is typed at the
end of command the output is not displayed (called suppress the output).

Scalar Variables and assignment in MATLAB


A variable is a name of a letter or a combination of server letters that is assigned a numerical value. Once
variable is assigned a numerical value, it can be used in mathematical expressions, functions etc. In MATLAB
the = sign is called assignment operator. The assignment operation assigns a value to a variable.

Variable_name=A numerical value, or a computable expression

 1×1-matrices are called scalars.


 No declaration of variables (matrix is the keyword). These are defined by assignment.
 Assignments are done by = ended by Enter.

Rules for variable name


 Name can be up to 63 character long.
 Can contain letters, digits, and the underscore character.
 Must begin with letter.
 Avoid using the name of built-in function for a variable. Once a function name is used to define a variable,
the function can not be used.
Practice 3
>> a=12 %Assign 12 to a
a = 12

>> B=4 %Assign 4 to B


B= 4

>> C=(a-B)+40-a/B*10 %Assign the value of the expression to the variable C


C = 18

>>x=0.75; %Once a variable is defined it can be used as an argument


>>E=sin(x)^2+cos(x)^2
E=1

2 Numerical Methods – Fundamental Concepts


Predefined Variables
Several frequently used variables are already defined when MATLAB is started. Some are listed here.
Ans A variable that has the value of the last expression that was not assigned to a specific variable.
pi The number π (3.1416)
eps The smallest difference between two number Equal to 2^ (-52), which is appx 2.2204e-016.
inf Used for infinity.
i Defined as (-1) ^ (1/2), which is 0+1.0000i
j Same as i.
NaN Stands for Not a Number. Used when MATLAB cannot determine a valid numeric value. (0/0)
Practice 4: Trigonometric identity
A trigonometric identity is given by
cos2(x/2)=(tan x +sin x)/2tax x
Variable that the identity is correct by calculating each side of the equation, substituting x=π/5
>> x=pi/5;

>> LHS=cos(x/2)^2
LHS = 0.9045

>> RHS=(tan(x)+sin(x))/(2*tan(x))
RHS = 0.9045

Creating Matrix/Arrays
The Matrix/Array is a fundamental form that MATLAB uses to store and manipulate data. It is a list of numbers
arranged in rows and/or columns. Simplest way to create matrix is to use the constructor operator [].
One Dimensional
It is a list of numbers that is placed in a row or a column. Variable_name=[ type vector elements]
Row Vector: To create a row vector type the element with a space or a comma between the elements inside
square brackets.
row = [E1, E2, … Em] or row = [E1 E2 … Em]
>>A=[12, 62, 93, -8, 22]
Column Vector: To create a column vector type the element with a semicolon between the element or press the
enter key after each element inside square brackets.
col = [E1; E2; … Em] or row = [E1
E2
… Em]
>>B=[12; 62; 93; -8; 22]
Example Date
Year 2007 2008 2009 2010
Population 136 158 178 211
(Millions

Practice 1
>> yr=[2007 2008 2009 2010] %Year is assigned to a row vector named yr.
Matrix
yr creation
= 2007 using
2008: Operator
2009 (colon)
2010
Colon operator is used to create a vector with constant spacing the difference between the elements is the same.
>> pop=[136; 158; 178; 211] %Population data is assigned to column vector named
Variable_name=[ start : step : stop] or start : step : stop
pop.
Wherepop
start
= is first term, stop is last term and step is spacing between elements. The default value of step is 1.
136 Practice 2
158 >> yr=[2007 : 2010] %Year is assigned to a row vector named
178 yr.
yr = 2007 2008 2009 2010
3 Numerical
>> x=[1: 2 :Methods
13] – Fundamental Concepts%First element is 1, spacing 2 and last 13
x = 1 3 5 7 9 11 13
>> y=[1.5: 0.1 : 2.1]
y = 1.5000 1.6000 1.7000 1.8000 1.9000 2.0000 2.1000
>> x = -pi/2:2*pi/60:pi/2;
Note: If stop value can not be obtained by add step’s to stop then the last element is the vector with be last
number that does not exceed stop.

Matrix creation using linspace function


The linspace function is used to generate a row vector of n linearly equally spaced elements.
Variable_name=linspace( start, stop, n)
Where start is first element, stop is last element and n is the total number of elements are created. The default
value of n is 100.

Two Dimensional
A two dimensional array/matrix has numbers in rows and columns. Matrix can be used to store information like
in a table.
Variable_name=[ 1st row elements; 2nd row elements; ……. ;last row elements ]

To create a matrix type the element with a semicolon between the rows or press the enter key after each row
inside square brackets.
row = [RE1; RE2; … REm] or row = [RE1
RE2
… REm]
Practice 4
>> a=[5 35 43; 4 76 81; 21 32 40] %A semicolon is typed before a new line

>> b= [ 7 2 76 33 8 %Press enter before a new row


1 98 6 25 6
5 54 68 9 0]

>> cd=6;e=3;h=4; %Three variable are defined


>> Mat=[e,cd*h,cos(pi/3);h^2,sqrt(h*h/cd),14]
Mat = %Elements are defined by expressions
3.0000 24.0000 0.5000
16.0000 1.6330 14.0000
Matrix Addressing
 The address of an element in a matrix is its position defined by the row and column.
 A matrix named ma, ma(k,p) refers to the element in row k and column p.
 The first row and column position is 1.
 You can change the value of any element by address like this ma(k,p)=new value.
Practice 8
>> MAT=[3 11 6 5; 4 7 10 2; 13 9 0 8]; %Create a 3x4 matrix

>> MAT(3,1) %Display the first element in third row


ans= 13

>> MAT(3,1)=20 %Assign a new value to (3,1) element.


MAT= 3 11 6 5
4 7 10 2
20 9 0 8

>> MAT(2,4)- MAT(1,2) %Use of vector element in expressions


ans= -9

Use of : (colon) in vector addressing

4 Numerical Methods – Fundamental Concepts


A colon can be used to address the range of elements in vector
ve(:) Refers to all the element of the row or column vector ve
ve(m:n) Refers to elements m through n of the vector ve

Practice 9
>> ve=[4 15 8 12 34 2 50 23 11]; %A vector ve is created

>> u=ve(3:7) %A vector u is created from ve(3 through


7)

Element by element operation


 When operation applied on each element is said to be element by element. Addition and subtraction are by
definition already element by element operations but multiplication, division and exponential are done by
using . (dot) operator.
 This operation is applied on two arrays then must be the same size of both arrays but one of them can be a
scalar.
 If two vectors a and b are: a=[a1 a2 a3] and b=[b1 b2 b3] then element by element of the two vectors as follows
a.*b = [a1*b1 a2*b2 a3*b3] a./b = [a1/b1 a2/b2 a3/b3] a.^b = [a1^b1 a2^b2 a3^b3]
Symbol Description Symbol Description
.* Multiplication ./ Right division
.^ Exponential .\ Left division

Practice 18
>> A=[2 6 3; 5 8 4];

>>B=[1 4 10; 3 2 7];

>> A.*B %Element by element multiplication of array.


ans= 2 24 30
15 16 28

>> C=A./B; % Element by element division of array

Graphics
MATLAB produce two and three dimensional plots of curves and surface
Two Dimensional Plots
 Plots are very useful tool for presenting information.
 Plot title, Legend, X axis label, Y axis label, Text label and Markers.
 Graph is shown in figure window.

Plot Command
The plot command is used to create two dim plots.
The simplest from of the command is plot(x,y), Where x (horizental axis) and y (vertical axis) are vector.
Both vectors must have the same number of elements.
The curve is constructed of straight line segments that connect the points.
The figure that is created has axes with linear scale and default range.
Line Specifiers:
 Line specifiers are optional and can be used to define the style and coloar of the line and the type of
markers.
 Within the string the specifiers can be typed in any order.
 Specifier is optional i.e. None, one, two, or all the three can be included in command.

5 Numerical Methods – Fundamental Concepts


Line Style Specifier Line Color Specifier Marker Type Specifier
solid(default) - red r plus sign +
dashed -- green g circle o
dotted : blue b asterisk *
dash-dot -. cyan c point .
megenta m square s
yellow y diamond d
black k
white w
Practice 20 Plot y=sin(x) on interval -2 and 4
>> x=[-2:0.01:4];
>>y=sin(x);
>>plot(x,y,’r’)
>>plot(x,y,’r’);
>>plot(x,y,’--y’);
>>plot(x,y,’*’);
>>plot(x,y,’g:d’);

Plot of function
Plot of given functgion can be done in MATLAB by using the plot or the fplot commands.

Using plot: Plot a function y=f(x) with plot command, user first needs to create a vector of values of x for the
domain that function will be plotted.
Then a vector y is created with the corresponding values of f(x) by using element by element calculation
Plot the x and y vectors by using plot command.

Using fplot: Plot a function y=f(x) with fplot command between specified limits.

fplot(‘function’, limits, n, line specifiers)

function can be typed directly as a string and The function can not include previously defined variables.
limits is a vector with two element that specify the domain of x [xmin,xmax] or [xmin ,xmax,ymin,ymax].
n is the number of points between interval.
Line specifier are the same as in plot command.

Using the hold on, hold off commands


Hold on command keeps the figure window with first plot open, including the axis properties and formatting if
any was done.
Additional graphs can be added with plot command that is typed next.
Hold off command stops this process.
The grid command
grid on %adds grid lines to the plot
grid off %removes grid lines from the plot
Practice 22
Examples: y=cos(x), z=cos(x)2 for 0<=x<=pi
%Two or more graphs can be created in the same plot by typing pairs of vectros.
>>x=0:0.1:pi; % specifies the domain
>>y=cos(x); % define 1st function
>>z=cos(x).^2; % define 2nd function
>>plot(x,y,x,z,’o’) % display graph. (x, y 1st fun , x, y 2nd fun )

>>fplot(‘cos’,[-2,4])
6 Numerical Methods – Fundamental Concepts
>>hold on
>>fplot(‘sin’,[-2,4])
M-Files
 Files that contain a MATLAB code are called the m-files. There are two kinds of m-files:
1. script files
Script files is a sequence of MATLAB statements and do not take the input arguments or return the
output arguments
2. function files
The function files may take input arguments or return output arguments. Function name should be same
as the name of the file without .m extension
 To make the m-file click on File next select New and click on M-File
 To open the m-file from within the Command Window type >>edit filename
Script Files
 A Script file is a sequence of MATLAB command also call a program.
 When a script file runs, MATLAB executes the commands in the order they are written.
 When a script file displayed the output in command window.
 It is convenient way to edit and execute command many times.
 Script file can be typed and edited in any text editor and saved as .m file.
 Script files is also called M-files because the extension .m is used.
The input command
The input command is used to prmpt user to assign a value to variable in command window.
variable_name=input(‘string with a message that displayed in command windows’)
The string is a message prompting the user to enter a value that is assigned to variable.

The disp command


The input command is used to display the elements of a variable and to display text.
disp(name of the variable) or disp(‘text as string’)
Every time the disp command is executed, the display it at new line.
Practice 1
>>abc=[5 9 1; 7 2 4]; %A 2x3 array is assigned to variable abc.
>>disp(abc)
>>disp(‘The problem has no solution.’)

%Create a script file with name average.m


disp('Calcuate the average of points scored in three games');
game1=input('Enter the point scored in the first game ');
game2=input('Enter the point scored in the second game ');
game3=input('Enter the point scored in the third game ');
avg_points=(game1+game2+game3)/3;
disp(‘ ‘) %Dispaly empty line
disp(‘The average of points scored in a game is:’) %Dispaly text.
disp(‘ ‘) %Dispaly empty line
disp(avg_points) %Display value of the variable avg_points.
>>average

%Create a script file with name PopTable.m


yr=[1984:2:1996];
pop=[127 130 136 145 158 178 211]
tableYP(:,1)=yr’; %yr is entered as the first column in the array tableYP
tableYP(:,2)=pop’; %pop is entered as the second column in the array tableYP
disp(‘ YEAR POPULATION ‘) %Display heading first line
disp(‘ (MILLIONS)’) %Display heading second line
7 Numerical
disp(‘ ‘) Methods – Fundamental Concepts %Dispaly empty line
disp(tableYP) %Display the array tableYP.
>>PopTable
Using to display text
fprintf(‘text typed in as a string’)
\n used to start with new line in the middle of string.
\t used to insert horizontal tab in string
Using to display mixed text and numerical data
fprintf(‘text as string %-5.2f additional text’, variable_name)
- (optional) Left Justified + prints a sign character (+ or -)
5.2(optional) Field width and precision (optional)
f (required) Conversion character (required). Initial % Character

Practice 2
%Create a script file with name TempConv.m
disp('Converting table Cel 2 Fah');
start=input('Start temp in Celsius: ');
incr=input('In-crement in Celsius: ');
total=input('No of Entries in table: ');
stop=start+(total-1)*incr;
C=start:incr:stop;
F=9/5*C+32;
disp('Celsius Fahrenheit');
fprintf('%10.2f %10.2f \n', [C;F]);
>>TempConv

Function files
 A user defined function is a MATLAB program that is created by the user saved as function file, and then
can be used like a built in function.
 It must be put in a .m-file with same name as function
 The input and output can be one or several variables, and each can be a scalar, vector or an array of any size
 A large program can be made up of smaller “building blocks” that can be tested independently.
Structure of a function file

Practice 3
function [mpay, tpay]=loan(amount,rate,years) %function definition line
%loan calculates monthly and total payment of loan. %The H1 line
%Input arguments: % Help Text.
%amount=loan amount in $ “
%rate=annual interest rate in percent. “
%years=number of years.
%Output arguments:
%mpay=monthly payment, tpay=total payment.
format bank %function body
ratem=rate*0.01/12;
a=1+ratem;
b=(a^(years*12)-1)/ratem;
mpay=amount*a^(years*12)/(a*b); %Assignment of values to output
arg
tpay=mpay*years*12;

8 Numerical Methods – Fundamental Concepts


Function Definition Line
The first executable line in a function file must be the function definition line.
Defines the file as a function file
Defines the name of function
Defines the number and order of the input and ouput arguments.
function [output arguments]=function_name(input arguments)

Practice 4 FtoC.m
Function C = FtoC(F)
%FtoC converts degrees F to degrees C
C=5*(F-32)./9;

>>FC=inline(‘5*(F-32)./9’);
>>z=FC(70);

%f(x,y)=2x2-4xy+y2
>>HA=inline(‘2*x^2-4*x*y+y^2’);
>>z=HA(2,3)
z=-7

The feval Command


feval command evaluates the value of a function for given value of arguments.
Variable=feva(‘function name’, arguments value)
The function name typed as string
The function can be a built in or user defined function
More then one arguments are separated by commas.
More then one output are stored in matrix ([a,b,c, . . . . .])

Practice 5
>>feval(‘sqrt’,64)
ans=8
>>feval(‘FtoC’,70);
>>[M,T]=feval(‘loan’,50000,3.9,10)
M=502.22
T=60266.47

Summary:
In this lab practical students understand the programming concepts of MATLAB. These concepts are essential
for every student for implementation and analysis of Numerical Method.

Web Resources
http://www.mathworks.com/academia/student_center/tutorials/launchpad.html

Videos Resources
http://www.mathworks.com/videos/writing-a-MATLAB-program-69023.html

9 Numerical Methods – Fundamental Concepts


http://www.youtube.com/watch?v=QOJCvHUkJSs

10 Numerical Methods – Fundamental Concepts


EXERCISES

Exercise 1.1 [2]


Use MATLAB to show that the sum of the infinite series sum(1/n2) converges to pi2/6. Do it by computing the
sum for
n=100
n=1000
n=10000
n=100000

Exercise 1.2 [2]


Solve the following system of four linear equations
5x+4y-2z+6w=4
3x+6y+6z+4.5w=13.5
6x+12y-2z+16w=20
4x-2y+2z-4w=6

Exercise 1.3 [2]


Create a 6 x6 matrix in which the middle two rows and the middle two columns are 1’s and the rest are 0’s
Exercise 1.4 [2]
Using the eye command create the array A of order 7 x 7. Then using the colon to address the elements in the
array change the array as show bellow
2 2 2 0 5 5 5
2 2 2 0 5 5 5
3 3 3 0 5 5 5
A= 0 0 0 1 0 0 0
4 4 7 0 9 9 9
4 4 7 0 9 9 9
4 4 7 0 9 9 9
Exercise 1.5 [2]
Create a vector, name it Afirst, that has 16 equally spaced elements. First element is 4 and last element is 49.
Create a new vector, call it Asecond that has eight elements. The first four elements are the first four elements
of the vector Afirst, and the last four are the last four elements of the vector Afirst.

Exercise 1.6 [2]


Write a function that should take a number as input and calculate factorial of each and every number starting
from 0 to given input number. Input should be a fixed number and outputs should be an array of factorials.

Exercise 1.7 [2]


Write a function or script file that takes and input number n and give the prime numbers from 0 to n. All of
these numbers should be displayed in an array.

Exercise 1.8 [2]


Write a script file that calculates Fibonacci series up to some given range.

Exercise 1.9 [2]


Write a script file that should plot the function 3e2πft whose sampeling period should be 0.001 and frequency
should be 2. Color of final plot should be red and add legends; labels to the plot, line should be thick.

11 Numerical Methods – Fundamental Concepts

You might also like