Tuesday, July 16, 2019

[ MATLAB Tutorial - Lession 3] Command

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.
In this section, we will provide lists of commonly used general MATLAB commands.

Commands for Managing a Session

MATLAB provides various commands for managing a session. The following table provides all such commands −
CommandPurpose
clcClears command window.
clearRemoves variables from memory.
existChecks for existence of file or variable.
globalDeclares variables to be global.
helpSearches for a help topic.
lookforSearches help entries for a keyword.
quitStops MATLAB.
whoLists current variables.
whosLists current variables (long display).

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 −
CommandPurpose
cdChanges current directory.
dateDisplays current date.
deleteDeletes a file.
diarySwitches on/off diary file recording.
dirLists all files in current directory.
loadLoads workspace variables from a file.
pathDisplays search path.
pwdDisplays current directory.
saveSaves workspace variables in a file.
typeDisplays contents of a file.
whatLists all MATLAB files in the current directory.
wklreadReads .wk1 spreadsheet file.

Input and Output Commands

MATLAB provides the following input and output related commands −
CommandPurpose
dispDisplays contents of an array or string.
fscanfRead formatted data from a file.
formatControls screen-display format.
fprintfPerforms formatted writes to screen or file.
inputDisplays prompts and waits for input.
;Suppresses screen printing.
The fscanf and fprintf commands behave like C scanf and printf functions. They support the following format codes −
Format CodePurpose
%sFormat as a string.
%dFormat as an integer.
%fFormat as a floating point value.
%eFormat as a floating point value in scientific notation.
%gFormat in the most compact form: %f or %e.
\nInsert a new line in the output string.
\tInsert a tab in the output string.
The format function has the following forms used for numeric display −
Format FunctionDisplay up to
format shortFour decimal digits (default).
format long16 decimal digits.
format short eFive digits plus exponent.
format long e16 digits plus exponents.
format bankTwo decimal digits.
format +Positive, negative, or zero.
format ratRational approximation.
format compactSuppresses some line feeds.
format looseResets to less compact display mode.

Vector, Matrix and Array Commands

The following table shows various commands used for working with arrays, matrices and vectors −
CommandPurpose
catConcatenates arrays.
findFinds indices of nonzero elements.
lengthComputes number of elements.
linspaceCreates regularly spaced vector.
logspaceCreates logarithmically spaced vector.
maxReturns largest element.
minReturns smallest element.
prodProduct of each column.
reshapeChanges size.
sizeComputes array size.
sortSorts each column.
sumSums each column.
eyeCreates an identity matrix.
onesCreates an array of ones.
zerosCreates an array of zeros.
crossComputes matrix cross products.
dotComputes matrix dot products.
detComputes determinant of an array.
invComputes inverse of a matrix.
pinvComputes pseudoinverse of a matrix.
rankComputes rank of a matrix.
rrefComputes reduced row echelon form.
cellCreates cell array.
celldispDisplays cell array.
cellplotDisplays graphical representation of cell array.
num2cellConverts numeric array to cell array.
dealMatches input and output lists.
iscellIdentifies cell array.

Plotting Commands

MATLAB provides numerous commands for plotting graphs. The following table shows some of the commonly used commands for plotting −
CommandPurpose
axisSets axis limits.
fplotIntelligent plotting of functions.
gridDisplays gridlines.
plotGenerates xy plot.
printPrints plot or saves plot to a file.
titlePuts text at top of plot.
xlabelAdds text label to x-axis.
ylabelAdds text label to y-axis.
axesCreates axes objects.
closeCloses the current plot.
close allCloses all plots.
figureOpens a new figure window.
gtextEnables label placement by mouse.
holdFreezes current plot.
legendLegend placement by mouse.
refreshRedraws current figure window.
setSpecifies properties of objects such as axes.
subplotCreates plots in subwindows.
textPlaces string in figure.
barCreates bar chart.
loglogCreates log-log plot.
polarCreates polar plot.
semilogxCreates semilog plot. (logarithmic abscissa).
semilogyCreates semilog plot. (logarithmic ordinate).
stairsCreates stairs plot.
stemCreates stem plot.

[ Matlab Tutorial - Lession 2] Variables

In MATLAB environment, every variable is an array or matrix.
You can assign variables in a simple way. For example,
 Live Demo
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. Let us check another example,
 Live Demo
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.
  • 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,
 Live Demo
sqrt(78)
MATLAB will execute the above statement and return the following result −
ans =  8.8318
You can use this variable ans −
 Live Demo
sqrt(78);
9876/ans
MATLAB will execute the above statement and return the following result −
ans =  1118.2
Let's look at another example −
 Live Demo
x = 7 * 8;
y = x * 7.89
MATLAB will execute the above statement and return the following result −
y =  441.84

Multiple Assignments

You can have multiple assignments on the same line. For example,
 Live Demo
a = 2; b = 7; c = a * b
MATLAB will execute the above statement and return the following result −
c = 14

I have forgotten the Variables!

The who command displays all the variable names you have used.
who
MATLAB will execute the above statement and return the following result −
Your variables are:
a    ans  b    c   
The whos command displays little more about the variables −
  • 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 −
Attr Name        Size        Bytes      Class
==== ====        ====        ====       ===== 
   a             1x1           8        double
   ans           1x70         757        cell
   b             1x1           8        double
   c             1x1           8        double

Total is 73 elements using 781 bytes     
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
            %  peacefully and unobtrusively 

Long Assignments

Long assignments can be extended to another line by using an ellipses (...). For example,
 Live Demo
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

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 −
 Live Demo
format long
x = 7 + 10/3 + 5 ^ 1.2
MATLAB will execute the above statement and return the following result−
x = 17.2319816406394
Another example,
 Live Demo
format short
x = 7 + 10/3 + 5 ^ 1.2
MATLAB will execute the above statement and return the following result −
x = 17.232
The format bank command rounds numbers to two decimal places. For example,
 Live Demo
format bank
daily_wage = 177.45;
weekly_wage = daily_wage * 6
MATLAB will execute the above statement and return the following result −
weekly_wage = 1064.70
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,
 Live Demo
format short e
4.678 * 4.9
MATLAB will execute the above statement and return the following result −
ans = 2.2922e+01
The format long e command allows displaying in exponential form with four decimal places plus the exponent. For example,
 Live Demo
format long e
x = pi
MATLAB will execute the above statement and return the following result −
x = 3.141592653589793e+00
The format rat command gives the closest rational expression resulting from a calculation. For example,
 Live Demo
format rat
4.678 * 4.9
MATLAB will execute the above statement and return the following result −
ans = 34177/1491 

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,
 Live Demo
r = [7 8 9 10 11]
MATLAB will execute the above statement and return the following result −
r =

   7    8    9   10   11 
Another example,
 Live Demo
r = [7 8 9 10 11];
t = [2, 3, 4, 5, 6];
res = r + t
MATLAB will execute the above statement and return the following result −
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.
 Live Demo
c = [7;  8;  9;  10; 11]
MATLAB will execute the above statement and return the following result −
c =
       7       
       8       
       9       
      10       
      11  

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 −
 Live Demo
m = [1 2 3; 4 5 6; 7 8 9]
MATLAB will execute the above statement and return the following result −
m =
       1              2              3       
       4              5              6       
       7              8              9   

[ Matlab Tutorial - Lession 1] - 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.

Hands on Practice

Type a valid expression, for example,
 Live Demo
5 + 5
And press ENTER
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans = 10
Let us take up few more examples −
 Live Demo
3 ^ 2        % 3 raised to the power of 2
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans = 9
Another example,
 Live Demo
sin(pi /2)   % sine of angle 90o
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans = 1
Another example,
 Live Demo
7/0        % Divide by zero
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans = Inf
warning: division by zero
Another example,
 Live Demo
732 * 20.3 
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
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'.

Use of 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,
 Live Demo
x = 3;
y = x + 5
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
y =  8

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 % }.
The MATLAB editor includes tools and context menu items to help you add, remove, or change the format of comments.

Commonly used Operators and Special Characters

MATLAB supports the following commonly used operators and special characters −
OperatorPurpose
+Plus; addition operator.
-Minus; subtraction operator.
*Scalar and matrix multiplication operator.
.*Array multiplication operator.
^Scalar and matrix exponentiation operator.
.^Array exponentiation operator.
\Left-division operator.
/Right-division operator.
.\Array left-division operator.
./Array right-division operator.
:Colon; generates regularly spaced elements and represents an entire row or column.
( )Parentheses; encloses function arguments and array indices; overrides precedence.
[ ]Brackets; enclosures array elements.
.Decimal point.
…Ellipsis; line-continuation operator
,Comma; separates statements and elements in a row
;Semicolon; separates columns and suppresses display.
%Percent sign; designates a comment and specifies formatting.
_Quote sign and transpose operator.
._Nonconjugated transpose operator.
=Assignment operator.

Special Variables and Constants

MATLAB supports the following special variables and constants −
NameMeaning
ansMost recent answer.
epsAccuracy of floating-point precision.
i,jThe imaginary unit √-1.
InfInfinity.
NaNUndefined numerical result (not a number).
piThe number π

Naming Variables

Variable names consist of a letter followed by any number of letters, digits or underscore.
MATLAB is case-sensitive.
Variable names can be of any length, however, MATLAB uses only first N characters, where N is given by the function namelengthmax.

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
Back to Top