0% found this document useful (0 votes)
18 views

1 Introduction To MATLAB

This document provides an introduction and overview of MATLAB. It discusses the advantages and disadvantages of MATLAB, the MATLAB environment including the desktop layout and main panels, basic syntax used in MATLAB, variables, and commands. MATLAB is a numerical computing environment and programming language. It allows matrix manipulations, data visualization, algorithm implementation, user interface creation, and interfacing with other languages. The document outlines the key features and capabilities of MATLAB.

Uploaded by

we4kguy.gaming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

1 Introduction To MATLAB

This document provides an introduction and overview of MATLAB. It discusses the advantages and disadvantages of MATLAB, the MATLAB environment including the desktop layout and main panels, basic syntax used in MATLAB, variables, and commands. MATLAB is a numerical computing environment and programming language. It allows matrix manipulations, data visualization, algorithm implementation, user interface creation, and interfacing with other languages. The document outlines the key features and capabilities of MATLAB.

Uploaded by

we4kguy.gaming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

INTRODUCTION TO MATLAB

OVERVIEW AND ENVIRONMENT SETUP


TOPICS

• Overview
• The Advantages of MATLAB
• Disadvantages of MATLAB
• The MATLAB Environment
• Basic Syntax
• Variables
• Commands
MATLAB OVERVIEW

• MATLAB (matrix laboratory) is a fourth-generation high-level programming


language and interactive environment for numerical computation, visualization
and programming.
• MATLAB is a programming language developed by MathWorks.
• It allows matrix manipulations; plotting of functions and data; implementation
of algorithms; creation of user interfaces; interfacing with programs written in
other languages, including C, C++, Java, and FORTRAN; analyze data;
develop algorithms; and create models and applications.
• It has numerous built-in commands and math functions that help you in
mathematical calculations, generating plots, and performing numerical
methods.
THE ADVANTAGES OF MATLAB

1. Ease of Use
2. Platform Independence
3. Predefined Functions
4. Device-Independent Plotting
5. Graphical User Interface
6. MATLAB Compiler
DISADVANTAGES OF MATLAB

1. It is an interpreted language
2. Expensive
THE MATLAB ENVIRONMENT
MATLAB development IDE can be launched from the icon created on the desktop.
The main working window in MATLAB is called the desktop. When MATLAB is
started, the desktop appears in its default layout −
THE MATLAB ENVIRONMENT
• Current Folder − This panel allows you to access the project folders and files.
THE MATLAB ENVIRONMENT
• Command Window − This is the main area where commands can be entered at
the command line. It is indicated by the command prompt (>>).
THE MATLAB ENVIRONMENT
• Workspace − The workspace shows all the variables created and/or imported
from files.
THE MATLAB ENVIRONMENT
• Command History − This panel shows or return commands that are entered at
the command line.
MATLAB – BASIC SYNTAX
MATLAB environment behaves like a super-complex calculator. You can enter
commands at the >> command prompt.
MATLAB is an interpreted environment. In other words, you give a command and
MATLAB executes it right away.

Hand on Practice

• Type a valid expression, for example  >> 5+ 5


• And Press ENTER  ans = 10

Another example,

>> sin(pi/2) % sine of angle 90 degrees


ans = 1
MATLAB – BASIC SYNTAX
Another example,

>> 7/0 % Divide by zero


ans = Inf
Warning: division by zero

Another example,

>> 732 * 20.3


ans = 1.4860e+04

MATLAB provides some special expressions for some mathematical symbols like pi
for 𝜋𝜋, Inf for ∞, I (and j) for √-1 etc. Nan stands for ‘not a number’.
MATLAB – BASIC SYNTAX
Use Semicolon (;) in MATLAB

Semicolon (;) indicates end of statement. However, if you want to suppress and hide
the MATLAB output for an expression, add a semicolon after the expression.
For example,

>> x = 3;
>> y = x + 5
y=8
MATLAB – BASIC SYNTAX
Adding Comments

The percent symbol (%) is used for indicating a comment line. For example,

>> x = 9 % assign the value 9 to x

You can also write a block of comments using the block comment operators
% { and % }
MATLAB – BASIC SYNTAX
Commonly Used Operators and Special Characters
MATLAB supports the following commonly used operators and special characters −
Operator Purpose Operator Purpose
+ Plus; addition operator. () Parentheses; encloses function arguments and
array indices; overrides precedence.
- Minus; subtraction operator.
[] Brackets; enclosures array elements.
* Scalar and matrix multiplication operator. . Decimal point.
.* Array multiplication operator. … Ellipsis; line-continuation operator
, Comma; separates statements and elements in
^ Scalar and matrix exponentiation operator. a row
.^ Array exponentiation operator. ; Semicolon; separates columns and suppresses
display.
\ Left-division operator.
% Percent sign; designates a comment and
/ Right-division operator. specifies formatting.
_ Quote sign and transpose operator.
.\ Array left-division operator.
._ Nonconjugated transpose operator.
: Colon; generates regularly spaced = Assignment operator.
elements and represents an entire row or
column.
MATLAB – BASIC SYNTAX
Special Variables and Constants
MATLAB supports the following special variables and constants −

Name Meaning

ans Most recent answer.

eps Accuracy of floating-point precision.

i,j The imaginary unit √-1.

Inf Infinity.

NaN Undefined numerical result (not a number).

pi The number π
MATLAB – BASIC SYNTAX
Naming Variables

Variable names consist of a letter followed by any number of letters, digits or


underscore.

Variable names can be of any length, however, MATLAB uses only first N characters,
where N is given by the function namelengthmax.

MATLAB is case-sensitive.
MATLAB – BASIC SYNTAX
Saving Your Work

The save command is used for saving all the variables in the workspace,
as a file with .mat extension, in the current directory.

For example,

>> save myfile

You can reload the file anytime later using the load command.

>> load myfile


MATLAB – VARIABLES
In MATLAB environment, every variable is an array or matrix.
You can assign variables in a simple way. For example,

>> x = 3 % defining x and initializing it with a value

MATLAB will execute the above statement and return the following result −

x=3

It creates a 1-by-1 matrix named x and stores the value 3 in its element.
MATLAB – VARIABLES
Let us check another example,
>> x = sqrt(16) % defining x and initializing it with an expression

MATLAB will execute the above statement and return the following result −
x=4

Please note that −


• Once a variable is entered into the system, you can refer to it later.
• Variables must have values before they are used.
MATLAB – VARIABLES
• When an expression returns a result that is not assigned to any
variable, the system assigns it to a variable named ans, which can be
used later. For example,

>> sqrt(78)

MATLAB will execute the above statement and return the following result −

ans = 8.8318
MATLAB – VARIABLES
You can use this variable ans −
>> sqrt(78);
>> 9876 / ans
MATLAB will execute the above statement and return the following result −
ans = 1118.2

Let’s look another example –


>> x = 7 * 8;
>> y = x * 7.89
MATLAB will execute the above statement and return the following result −
y = 441.84
MATLAB – VARIABLES
Multiple Assignments

You can have multiple assignments on the same line. For example,
>> a = 2; b = 7; c = a * b
MATLAB will execute the above statement and return the following result −
c = 14
MATLAB – VARIABLES
The who command displays all the variable names you have used.

>> who
Your variables are:
a ans b c
MATLAB – VARIABLES
The whos command displays all the variable names you have used.
• Variables currently in memory
• Type of each variables
• Memory allocated to each variable
• Whether they are complex variables or not

>> whos
MATLAB will execute the above statement and return the following result -

Name Size Bytes Class Attributes


a 1x1 8 double
ans 1x70 757 cell
b 1x1 8 double
c 1x1 8 double
MATLAB – VARIABLES
The clear command deletes all (or the specified) variable(s) from the
memory.
>> clear x % it will delete x, won’t display anything
>> clear % it will delete all variables in the workspace
MATLAB – VARIABLES
Long Assignments can be extended to another line by using an
ellipses(…)
>> initial-velocity = 0;
>> acceleration = 9.8;
>> time = 20;
>> final_velocity = initial_velocity + acceleration …
* time

MATLAB will execute the above statement and return the following result -

final_velocity = 196
MATLAB – VARIABLES
The format Command

By default, MATLAB displays numbers with four decimal place values. This
is known as short format.
However, if you want more precision, you need to use the format command.
The format long command displays 16 digits after decimal.
For example −

>> fomat long


>> x = 7 + 10 / 3 + 5 ^ 1.2
x = 17.2319816406394
MATLAB – VARIABLES
The format Command
Another example −
>> format short
>> x = 7 + 10 / 3 + 5 ^ 1.2
x = 17.232

The format bank command rounds numbers to two decimal places. For
example,
>> format bank
>> daily_wage = 177.45; weekly_wage = daily_wage * 6
weekly_wage = 1064.70
MATLAB – VARIABLES
MATLAB displays large numbers using exponential notation.
The format short e command allows displaying in exponential form with
four decimal places plus the exponent.
For example,
>> format short e
>> 4.678 * 4.9
ans = 2.2922e+01
The format long e allows displaying in exponential form with fourteen
decimal places plus the exponent. For example,
>> format long e
>> x = pi
x = 3.14159265358979e+80
MATLAB – VARIABLES
The format rat command gives the closest rational expression resulting from
a calculation. For example,
>> format rat
>> 4.678 * 4.9
ans = 2063 / 90
MATLAB – VARIABLES
Creating Vectors
A vector is a one-dimensional array of numbers. MATLAB allows creating two types of
vectors −
• Row vectors
• Column vectors

Row vectors are created by enclosing the set of elements in square brackets, using
space or comma to delimit the elements.

For example,
>> r = [7 8 9 10 11]
r= 7 8 9 10 11
MATLAB – VARIABLES
Another example,
>> r = [7 8 9 10 11];
>> t = [2, 3, 4, 5, 6];
>> res = r + t
res = 9 11 13 15 17

Column vectors are created by enclosing the set of elements in square brackets, using
semicolon(;) to delimit the elements.
>> c = [7; 8; 9; 10; 11]
c= 7
8
9
10
11
MATLAB – VARIABLES
Creating Matrices
A matrix is a two-dimensional array of numbers.
In MATLAB, a matrix is created by entering each row as a sequence of space or comma
separated elements, and end of a row is demarcated by a semicolon. For example, let
us create a 3-by-3 matrix as −

>> m = [1 2 3; 4 5 6; 7 8 9]
c= 1 2 3
4 5 6
7 8 9
MATLAB – COMMANDS
MATLAB is an interactive program for numerical computation and data visualization.
You can enter a command by typing it at the MATLAB prompt '>>' on the Command
Window.
MATLAB provides various commands for managing a session. The following table
provides all such commands −
Command Purpose
clc Clears command window.
clear Removes variables from memory.
exist Checks for existence of file or variable.
global Declares variables to be global.
help Searches for a help topic.
lookfor Searches help entries for a keyword.
quit Stops MATLAB.
who Lists current variables.
whos Lists current variables (long display).
MATLAB – COMMANDS
Commands for Working with the System
MATLAB provides various useful commands for working with the system, like saving the
current work in the workspace as a file and loading the file later.
It also provides various commands for other system-related activities like, displaying
date, listing files in the directory, displaying current directory, etc.
The following table displays some commonly used system-related commands −
Command Purpose Command Purpose
cd Changes current directory. path Displays search path.
date Displays current date. pwd Displays current directory.
delete Deletes a file. save Saves workspace variables in a file.
diary Switches on/off diary file recording. type Displays contents of a file.
dir Lists all files in current directory. what Lists all MATLAB files in the current
directory.
load Loads workspace variables from a
file. wklread Reads .wk1 spreadsheet file.
MATLAB – COMMANDS
Input and Output Commands
MATLAB provides the following input and output related commands −

Command Purpose
disp Displays contents of an array or string.
fscanf Read formatted data from a file.
format Controls screen-display format.
fprintf Performs formatted writes to screen or
file.
input Displays prompts and waits for input.
; Suppresses screen printing.
MATLAB – COMMANDS
The fscanf and fprintf commands behave like C scanf and printf functions.
They support the following format codes −
Format Code Purpose
%s Format as a string.
%d Format as an integer.
%f Format as a floating point value.
%e Format as a floating point value in scientific notation.

%g Format in the most compact form: %f or %e.


\n Insert a new line in the output string.
\t Insert a tab in the output string.
MATLAB – COMMANDS
The format function has the following forms used for numeric display −

Format Function Display up to


format short Four decimal digits (default).
format long 16 decimal digits.
format short e Five digits plus exponent.
format long e 16 digits plus exponents.
format bank Two decimal digits.
format + Positive, negative, or zero.
format rat Rational approximation.
format compact Suppresses some line feeds.
format loose Resets to less compact display mode.
MATLAB – COMMANDS
Vector, Matrix and Array Commands
The following table shows various commands used for working with arrays, matrices and
vectors −

Command Purpose Command Purpose


cat Concatenates arrays. size Computes array size.
find Finds indices of nonzero elements. sort Sorts each column.
length Computes number of elements. sum Sums each column.
linspace Creates regularly spaced vector.
eye Creates an identity matrix.
logspace Creates logarithmically spaced vector.
ones Creates an array of ones.
max Returns largest element.
min Returns smallest element. zeros Creates an array of zeros.
prod Product of each column. cross Computes matrix cross products.
reshape Changes size. dot Computes matrix dot products.
MATLAB – COMMANDS
Vector, Matrix and Array Commands

Command Purpose

det Computes determinant of an array.


inv Computes inverse of a matrix.
pinv Computes pseudoinverse of a matrix.
rank Computes rank of a matrix.
rref Computes reduced row echelon form.
cell Creates cell array.
celldisp Displays cell array.
cellplot Displays graphical representation of cell array.
num2cell Converts numeric array to cell array.
deal Matches input and output lists.
iscell Identifies cell array.
MATLAB – COMMANDS
Plotting Commands
MATLAB provides numerous commands for plotting graphs. The following table shows
some of the commonly used commands for plotting −
Command Purpose Command Purpose
axis Sets axis limits. close Closes the current plot.
fplot Intelligent plotting of functions. close all Closes all plots.
grid Displays gridlines. figure Opens a new figure window.
gtext Enables label placement by mouse.
plot Generates xy plot.
hold Freezes current plot.
print Prints plot or saves plot to a file.
legend Legend placement by mouse.
title Puts text at top of plot.
refresh Redraws current figure window.
xlabel Adds text label to x-axis. set Specifies properties of objects such as axes.
ylabel Adds text label to y-axis.
subplot Creates plots in subwindows.
axes Creates axes objects. text Places string in figure.
close Closes the current plot. bar Creates bar chart.
MATLAB – COMMANDS
Plotting Commands

Command Purpose
loglog Creates log-log plot.
polar Creates polar plot.
semilogx Creates semilog plot. (logarithmic abscissa).
semilogy Creates semilog plot. (logarithmic ordinate).
stairs Creates stairs plot.
stem Creates stem plot.

You might also like