Introduction To MATLAB
Introduction To MATLAB
MATLAB
• The name MATLAB stands for
2 ans =
ans = >>
1
09-Mar-21
ans = ans =
3.1416 NaN
• The equality sign is used to assign values to • If no name is introduced, result of the
variables: expression is saved in a variable named ans:
>> a=2; >> a+b
>> b=3*a
ans =
b=
8
6
23.140692632779267 2.3141e+01
Areej Abbas Abubaker 11 Areej Abbas Abubaker 12
2
09-Mar-21
• Use the command who to see names of the • Remember that by using the up arrow key you
variables, currently available in the workspace. can see the commands you have entered so
far.
• To see a list of variables together with
information about their size, bytes…, use the
command whos.
• In order to delete a variable from the memory
use the clear a command.
• The clc command clears the command window
and homes the cursor.
m= m=
1 2 3 1 2 7
4 5 6 4 5 6
Areej Abbas Abubaker 15 Areej Abbas Abubaker 16
3
09-Mar-21
4
09-Mar-21
• Two useful array functions are size, which gives the Array Arithmetic
size of the array, and length, which gives the
maximum length of the array:
• Multiplying a scalar to an array, multiplies all the
elements by the scalar:
>> size(w) >> a=[1,2,4;2:4;4:0.5:5]
>> b=2*a
ans = • Only two arrays of the same size may be added
or subtracted:
3 11 >> c=ones(3);
>> a-c
>> length(w)
>> a+c
• Adding a scalar to an array results in adding the
ans = scalar to all the elements of the array:
>> a+2
11 Areej Abbas Abubaker 25 Areej Abbas Abubaker 26
5
09-Mar-21
6
09-Mar-21
Scripts
• Return to the MATLAB command window and
• Calculate the volume of a cylindrical tank:
type, and input the required data and see the
% Calculation of volume of a cylindrical tank results:
clc
disp('Calculating the volume of a cylindrical tank ')
d=input('Vector of diameters (m)=');
>> Volume
h=input('the height (m)='); Calculating the volume of a cylindrical tank
a=pi*d^2; % the area of the base Vector of diameters (m)=[1:0.5:5]
v=a*h;
plot(d,v) the height (m)=2
xlabel('d(m)')
ylabel('V (m^3)')
title('Volume of Tank vs Diameter')
Areej Abbas Abubaker 37 Areej Abbas Abubaker 38
Functions
• You can develop your own function and
execute it just like other built-in functions in
MATLAB.
• A function takes some data as input, performs
required calculations, and returns the results
of the calculations back to you.
• As an example, let us write a function to
calculate the volume of a cylindrical tank, that
we have already done in a script.
Areej Abbas Abubaker 39 Areej Abbas Abubaker 40
>> h=2;
M.file >> d0=[1:0.5:5];
function v =tank(d,h) >> volume=tank(d,h);
% Calculation of volume of a cylindrical tank >> plot(d,volume)
for k=1:length(d) >>
v(k,:)=pi*d(k)^2*h; % Ideal gas law
end
end