Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Introduction To Matlab: Appendix

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

APPENDIX 6

Source: B.D. Agarwal, L. J. Broutman, K. Chandrashekhara, Analysis and Performance


of Fiber Composites, John Wiley, 2018 (Fourth Edition)

INTRODUCTION TO
MATLAB

MATLAB is a widely used software for numerical computations, visualizations,


and programming. It is user friendly and easy to operate interactively with inbuilt
mathematical subroutines. It is particularly useful for the analysis of composite
materials and structures, which may involve extensive matrix and vector
manipulations. A brief introduction of MATLAB is given below.

A6.1 INTRODUCTION: GETTING STARTED


At start, MATLAB default layout appears on the computer screen as shown in Fig.
A6-1 (the layout may vary for different versions). The layout provides a “Command
Window”, which is the main working area, a “Current Folder” and “Variables”
which stores all variables and their values.
In MATLAB, ‘>>’ indicates beginning of a command line. This prompt indicates
that MATLAB is ready to receive user command, process it and give output on the
next line. For example, when the following statement is typed on the command line:

>> a=2

MATLAB creates variable 𝑎𝑎 in the workspace (or adds it to the existing variables)
and assigns it a value ‘2’. It displays the result in the command window as follows:

a =
2

To add variable 𝑏𝑏 with a value ‘6’, the following command is typed and result
displayed:
>>b=6
b=
6
Now, if a + b is typed on the command line, MATLAB calculates the indicated
sum and displays the following:
>>a+b
ans =
8
MATLAB stores the result or answer (ans) as a new variable for later calculations.
It can be given a different name by the user.
Variable name can be a combination of letters, digits and underscores but must
begin with a letter. It should be noted that MATLAB distinguishes between
uppercase and lowercase characters for variables and commands. MATLAB, by
default, displays output in the command window. However, display of output can
be suppressed by typing a semicolon at the end of command.
The following are few additional useful commands:
• clear or clear all removes all variables from the workspace
• who lists variables in workspace
• whos will give more details including size, space allocation, and class
of the variables
• clc clears the Command Window
• ctrl-c aborts a MATLAB computation
• To continue a line, type (….)

MATLAB has many inbuilt functions. The common mathematical operators


(including matrix operators) are given in the following table:

Operator Descriptions
+ addition
- subtraction
* multiplication
/ division
ʹ transpose
^ power

Some inbuilt trigonometric and advanced mathematical functions are tabulated


below:
Symbol Descriptions
cos(x) cosine
sin(x) sine
tan(x) tangent
acos(x) inverse cosine
asin(x) inverse sine
sinh(x) hyperbolic sine
cosh(x) hyperbolic cosine
tanh(x) hyperbolic tangent
conj(x) complex conjugate
exp(x) exponential
sqrt(x) square root
log(x) natural logarithm
log10(x) common logarithm
abs(x) absolute value
sign(x) signum function
max(x) maximum value
min(x) minimum value
ceil(x) round toward positive infinity
floor(x) round toward negative infinity

For example, sine of variable a is calculated as follows:


>> sin(a)
ans =
0.9093

A6.2. VECTORS AND MATRICES

A6.2.1 Defining Matrices


Matrix is entered row by row. Elements in a row are separated by comma (,) or
space whereas rows are separated by semicolons as shown below:

>> A = [1, 3, 10; 7 5 9; 6 8 3]

The entered matrix appears in the next line as

A =
1 3 10
7 5 9
6 8 3

The rows can also be typed on separate lines as shown below:

>> B = [ 2 5 6
9 0 1
8 4 7]
B =
2 5 6
9 0 1
8 4 7

A6.2.2 Basic Matrix Functions

Symbol Descriptions
size dimensions of matrix
det determinant of matrix
inv inverse of matrix
diag diagonal of a matrix
trace sum of diagonal elements of matrix
eye(n) identity matrix (n x n)
zeros(i,j) zero matrix (i x j)
eig eigenvalues and eigenvectors
rand(i, j) (i x j) matrix with uniformly random numbers

Examples:
>> size(A)
ans =
3 3

>>det(A)
ans =

302

>>inv(A)
ans =

-0.1887 0.2351 -0.0762


0.1093 -0.1887 0.2020
0.0861 0.0331 -0.0530

>>diag(A)
ans =

1
5
3

>>trace(A)
ans =

9
>>eye(3)
ans =

1 0 0
0 1 0
0 0 1

>>zeros(2,3)
ans =

0 0 0
0 0 0

>> [C L] = eig(A)

where the columns of C matrix give the eigenvectors, and the values of L matrix
gives eigenvalues. The output shows the following results:

C =
-0.4692 -0.8618 -0.8677
-0.6754 0.4374 0.1982
-0.5690 0.2569 0.4560

L =
17.4446 0 0
0 -3.5041 0
0 0 -4.9404

A6.2.3 Extracting Parts of Matrices


The following example show how a few columns or rows or sub matrices can be
extracted from the main matrix. Colon is a useful operator for these operations as
shown in the examples below.

Extracting 3rd column of matrix A:


>>A(:,3)
ans =
10
9
3

Extracting second row of matrix A:


>>A(2,:)
ans =
7 5 9

Extracting sub-matrix consisting of elements on the first two rows and the last
two columns of the matrix, then the commands lines are as follows:
>>A(1:2,2:3)
ans =
3 10
5 9

A6.2.4 Basic Matrix Operations


Addition:
>> A+B
ans =
3 8 16
16 5 10
14 12 10
Subtraction:
>> A-B
ans =
-1 -2 4
-2 5 8
-2 4 -4
Multiplication:
>> A*B
ans =
109 45 79
131 71 110
108 42 65

A6.3 PROGRAMMING IN MATLAB


Different elements of programming in MATLAB are given in this section.

A6.3.1 Logical and Relational Operators

Symbol Descriptions
</> less than/greater than
<= / >= less than / greater than or equal to
== equal
~= not equal
~ logical not
& logical and
| logical or
A6.3.2 Loop and Logical Statements

Symbol Descriptions
if a conditional statement
elseif, else used along with if command
for loop command
while loop command with conditional statement
break terminate loop execution

A6.3.3 MATLAB Functions: Saving Programs


MATLAB functions are like C Functions or Fortran subroutines. These can be
saved in text files with a name that has an extension ‘.m’. These files are called m-
files. A saved function can be recalled and executed by the file name.
MATLAB functions have two parameter lists, one for input and the other for
output. The first line of a function m-file must be of the following form.

function [out1, out2, …]=function_name(inp1, inp2, …)

The parameters on left hand side are output parameters and those on right hand
side are input parameters. Each function can have several input and output
parameters. Name of the above program is “function_name” and must be saved as
“function_name.m”.

Creation of a function can be further illustrated as follows: consider three


variables a, b and c which are each functions of three variables x, y and z. It is
desired to obtain values of a, b and c as output when values of x, y and z are given
as input. For this purpose, relationship between the functions and variables will be
defined first. The MATLAB function will be defined by typing the following:

function [a, b, c] = function_name(x, y, z)

This function must be stored as “function_name.m”. It can be later recalled and


executed.

Example: To calculate value of function g for any value of x where


g ( x) = (1 + x) 2 , the following MATLAB function is created:

function [g] = myfunction(x)


g = (1+x)^2

Value of g for x=6 is obtained as follows:

>> myfunction(6)
g = 49

A6.3.4 Input/Output Functions


These functions are like creating variables and are used to input data. Example
>> E=input ('Enter the Young’s modulus of elasticity-')
>> display(E)

A6.3.5 Controlling the Appearance of Floating Point Number


MATLAB displays calculated results to four decimal places, by default, but it can
display the values up to 15 decimal places. The display is controlled by the
command ‘format’.

% scaled fixed-point format with 4 digits after the decimal point


>> format short
% floating-point format, with 4 digits after the decimal point
>> format short e
% scaled fixed-point format with 14 to 15 digits after the decimal point for double;
and 7 digits after the decimal point for single
>> format long
% floating-point format, with 14 to 15 digits after the decimal point for double; and
7 digits after the decimal point for single
>> format long e

A6.4 PLOTTING TOOLS


MATLAB provides several options for plotting data. Some of the useful options are
tabulated below:
A6.4.1 Basic Plot Commands

Symbol Descriptions
plot(x,y) 2-D plot y vs. x
title(' ') add title to current axes
xlabel/ylabel(' ') add label to x-axis/y-axis
text(' ') add text on the plot window
gtext(' ') receive a text from mouse input
switch on/off the grid on the plot
grid on/off
window
allow to add another plot to the
hold on/off
current plot
axis([xmin xmax ymin ymax]) scale x and y axes
produce a coordinate of a point on the
ginput
plot screen
plot3(x,y,z) plot in 3D coordinate system
generate n linearly spaced points
linspace(a,b,n)
between a and b

Example:

>> x = linspace(0,360,180);
>> y1=sind(x);
>> y2=cosd(x);
>> plot(x,y1, 'k- ');
>> hold on;
>> plot(x,y2, 'k-- ');
>> legend('y1=sinx ', 'y2=cosx');
>> xlabel('\theta');
>> ylabel('y1&y2');
>> grid on;
>> axis([0 360 -1.1 1.1]);

The results are shown in the following Fig. A6-2:

A6.4.2 Line Styles and Colors


By default, MATLAB produces plots with solid lines and colors in the order of blue,
green and then red. However, the colors and styles of lines can be selected from the
options given in the table below:
Colors Line styles
b --blue . --point
g --green o --circle
r --red x --x-mark
y --yellow + --plus mark
c --cyan - --solid line
m --magneta -- --dashed line
w --white -. --dash dot
k --black * --star mark
: --dotted

The options are very convenient to differentiate between variables in the same
figure. Color and line style is controlled by adding a third argument in the plot
command. The first and second characters of this third argument specify the color
and the line style, respectively. The following example produces a dashed green
plot.

>> plot (x, y1, 'g--')


Menu bar Tool bar

Current
folder

Command window

Figure A6-1.
1 y1=sinx
y2=cosx
0.8

0.6

0.4

0.2
y1&y2

-0.2

-0.4

-0.6

-0.8

-1
0 50 100 150 200 250 300 360
θ
Figure A6-2.

You might also like