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

Traic Introduction of Matlab: (Basics)

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

TRAIC

Introduction of
MATLAB
(BasicS)

-Arun PAnwaR
Electrical and Electronics Engg.

(2010-14)

College Of Engg. Roorkee


What is Matlab?
MATLAB (matrix laboratory) is a high-level language and interactive environment for
numerical computation, visualization, and programming. Using MATLAB, you can
analyse data, develop algorithms, and create models and applications. The language,
tools, and built-in math functions enable you to explore multiple approaches and
reach a solution faster than with spreadsheets or traditional programming languages,
such as C/C++ or Java.

History
Cleve Moler, the chairman of the Computer science department at the University of
New Mexico, started developing MATLAB in the late 1970s. He designed it to give
his students access to and EISPACK without them having to learn Fortran. It soon
spread to other universities and found a strong audience within the applied
mathematics community. John N. Little, an engineer, was exposed to it during a visit
Moler made to Stanford University in 1983. Recognizing its commercial potential, he
joined with Moler and Steve Bangert. They rewrote MATLAB in C (programming
language) and founded MathWorks in 1984 to continue its development. These
rewritten libraries were known as JACKPAC. In 2000, MATLAB was rewritten to
use a newer set of libraries for matrix manipulation, LAPACK.
MATLAB was first adopted by researchers and practitioners in Control engineering,
Little's specialty, but quickly spread to many other domains. It is now also used in
education, in particular the teaching of Linear algebra and Numerical analysis, and is
popular amongst scientists involved in Image processing.

Strengths
MATLAB may behave as a calculator or as a programming language
MATLAB combine nicely calculation and graphic plotting.
MATLAB is relatively easy to learn
MATLAB is interpreted (not compiled), errors are easy to fix
MATLAB is optimized to be relatively fast when performing matrix
operations
MATLAB does have some object-oriented elements
Competition
One of MATLAB's competitors is Mathematica, the symbolic computation
program.
MATLAB is more convenient for numerical analysis and linear algebra. It is
frequently used in engineering community.
Mathematica has superior symbolic manipulation, making it popular among
physicists.
There are other competitors:
o Scilab
o GNU Octave
o Rlab
Desktop basic

Current Folder Access your files.


Command Window Enter commands at the command line,
indicated by the prompt (>>).
Workspace Explore data that you create or import from
files( all the variables you create or import)
Command History View or rerun commands that you
entered at the command line.
(Store all the commands you have written)
Getting started
Creating MATLAB variables
MATLAB variables are created with an assignment statement. The syntax of variable
as-
variable name = a value (or an expression)

For example,
>> x = expression

where expression is a combination of numerical values, mathematical operators,


variables, and function calls. On other words, expression can involve:
manual entry
built-in functions
user-defined functions

Overwriting variable
Once a variable has been created, it can be reassigned or overwrite. In addition, if you
do not wish to see the intermediate results, you can suppress the numerical output by
putting a semicolon (;) at the end of the line. Then the sequence of commands looks
like this:
Error messages
If we enter an expression incorrectly, MATLAB will return an error message. For
example, in the following, we left out the multiplication sign, *, in the following
expression

Use of brackets

Controlling the appearance of floating point number


MATLAB by default displays only 4 decimals in the result of the calculations, for
example
Managing the workspace
The contents of the workspace persist between the executions of separate commands.
Therefore, it is possible for the results of one problem to have an erect on the next
one. To avoid this possibility, it is a good idea to issue a clear command at the start of
each new independent calculation.

>> clear

The command clear or clear all removes all variables from the workspace. This
frees up system memory. In order to display a list of the variables currently in the
memory,

>> who

Will give all the variable available in workspace.

>>whos
Will give more details which include size, space allocation, and class of the variables.

>>save

Will save all the variable of workspace in mat format

>>load filename.mat
Extract all the variable from filename.mat to workspace

#whos, clear, save commands can be used for particular variables to know detail of
variable, clear particular variable or to save particular variables respectively as-
Miscellaneous commands
Here are few additional useful commands:
To clear the Command Window, type clc
To abort a MATLAB computation, type ctrl-c
To continue a line, type . . .
To close the figure, type close, close all hidden and close all hidden
To write comment , type % then comment.
Eg:-

Getting help
Help Browser can be started by selecting the ? icon from the desktop toolbar.

We can also get information about any command is available by typing


>> help Command
Matrices and Arrays
Creating

#To create a matrix that has multiple rows, separate the rows with semicolons.

magic(n)
creates the magic matrix of size n*n

randi(m,n)
creates the random matrix of integers of size m*n
rand(m,n)
creates the random matrix of size m*n, with all elements less than 1
Operation

Athematic operations
+ , - , * , / ^ basic operators
.* , . / , .^ used for element to element wise multiplication or division
or power respectively.
Eg:
Other operations
Inverse of matrix

Transpose of matrix
Concatenation
Concatenation is the process of joining arrays to make larger ones. In fact,
you made your first array by concatenating its individual elements. The pair of square brackets [
] is the concatenation operator.
Other functions
MATLAB provide various function like:-
max(matrixname) provide highest element of each row

min(matrixname) will return lowest element of each row


sum(matrixname) will return sum of all the elements of each row
det(matrixname) will return determinant of the matrix
inv(matrixname) will return the inverse of matrix
size(matrixname) will return the size of matrix
Array Indexing

Every variable in MATLAB is an array that can hold many numbers. When
you want to access selected elements of an array, use indexing.

We can also change any element of matrix by


Character Strings
A character string is a sequence of any number of characters enclosed in single
quotes. You can assign a string to a variable.

If the text includes a single quote, use two single quotes within the definition.
2-D and 3-D Plots
Line Plots
#We can also plot other wave on same graph by using command hold on
3-D Plots
Three-dimensional plots typically display a surface defined by a function in
two variables, z = f (x,y).
Subplots
You can display multiple plots in different subregions of the same window
using the subplot function.
Matlab Programing

Till now we write all the commands in command window. The main problem is
that the commands entered in the Command Window cannot be saved and executed
again for several times. Therefore, a different way of executing repeatedly commands
with MATLAB is:
1. to create a file with a list of commands,
2. save the file, and
3. run the file.

If needed, corrections or changes can be made to the commands in the file. The files
that are used for this purpose are called script files or scripts for short.
This section covers the following topics:
M-File Scripts
M-File Functions
M-File Scripts

M-file function
Input and output commands used in script
Relational and logical operators
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
~= Not equal to
&& AND operator
|| OR operator
NOT operator
The if...end' structure
if ... end
if ... else ... end
if ... elseif ... else ... end

Syntax:
if expression
statement
else if expression
statement
else
statement
end

The for...end loop


In the for ... end loop, the execution of a command is repeated at a fixed and
predeter-mined number of times.

Syntax:
for variable = expression
statements
end
The while...end loop
This loop is used when the number of passes is not specified. The looping continues
until a stated condition is satisfied. The statements are executed as long as expression
is true. The while loop has the form:
Syntax:
while expression
statements
end
Summary of commands
Table A.1: Arithmetic operators and special characters

Character Description
+ Addition
- Subtraction
* Multiplication (scalar and array)
/ Division (right)
^ Power or exponentiation
: Colon; creates vectors with equally spaced elements
; Semi-colon; suppresses display; ends row in array
, Comma; separates array subscripts
Continuation of lines
% Percent; denotes a comment; specifes output format
Single quote; creates string; specifes matrix transpose
= Assignment operator
() Parentheses; encloses elements of arrays and input arguments
[] Brackets; encloses matrix elements and output arguments
Table A.2: Array operators

Character Description

.* matrix element wise multiplication


./ matrix element wise division
.^ Array power
Array (nonconjugated) transpose
Table A.3: Relational and logical operators

Character Description

< Less than


<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to
&& Logical or element-wise AND
|| Logical or element-wise OR

Table A.4: Managing workspace and file commands

Commands Description
cd Change current directory
clc Clear the Command Window
clear all Removes all variables from the workspace
clear x Remove x from the workspace
copy file Copy file or directory
delete Delete files
dir Display directory listing
exist Check if variables or functions are defned
help Display help for MATLAB functions
mkdir Make new directory
movefile Move file or directory
pwd Identify current directory
rmdir Remove directory
type Display contents of file
what List MATLAB files in current directory
which Locate functions and files
who Display variables currently in the workspace
whos Display information on variables in the workspace
Table A.5: Predefined variables and math constants
Variable Description
Ans Value of last variable for which no name assigned (answer)
Eps Floating-point relative accuracy
I Imaginary unit of a complex number
Inf Infinity Imaginary unit of a complex number
J Not a number
NaN The number (3:14159 )
Pi

Table A.6: Elementary matrices and arrays

Command Description
eye Identity matrix
linespace Generate linearly space vectors
ones Create array of all ones
rand Uniformly distributed random numbers and arrays
zeros Create array of all zeros

Table A.7: Arrays and Matrices: Basic information

Command Description
disp Display text or array
isempty Determine if input is empty matrix
isequal Test arrays for equality
length Length of vector
ndims Number of dimensions
numel Number of elements
size Size of matrix
max Greatest element
min Smallest element
det Determinant of matrix
inv Inverse of matrix
Contact Us:
Website: http://traic.in
E-mail: traic.mail@gmail.com

You might also like