The colon(:) is one of the most useful operator in MATLAB. It is used to create vectors, subscript arrays, and specify for iterations.
If you want to create a row vector, containing integers from 1 to 10, you write −
1:10
MATLAB executes the statement and returns a row vector containing the integers from 1 to 10 −
ans =
1 2 3 4 5 6 7 8 9 10
If you want to specify an increment value other than one, for example −
100: -5: 50
MATLAB executes the statement and returns the following result −
ans =
100 95 90 85 80 75 70 65 60 55 50
Let us take another example −
0:pi/8:pi
MATLAB executes the statement and returns the following result −
ans =
Columns 1 through 7
0 0.3927 0.7854 1.1781 1.5708 1.9635 2.3562
Columns 8 through 9
2.7489 3.1416
You can use the colon operator to create a vector of indices to select rows, columns or elements of arrays.
The following table describes its use for this purpose (let us have a matrix A) −
Format
Purpose
A(:,j)
is the jth column of A.
A(i,:)
is the ith row of A.
A(:,:)
is the equivalent two-dimensional array. For matrices this is the same as A.
A(j:k)
is A(j), A(j+1),…,A(k).
A(:,j:k)
is A(:,j), A(:,j+1),…,A(:,k).
A(:,:,k)
is the kth page of three-dimensional array A.
A(i,j,k,:)
is a vector in four-dimensional array A. The vector includes A(i,j,k,1), A(i,j,k,2), A(i,j,k,3), and so on.
A(:)
is all the elements of A, regarded as a single column. On the left side of an assignment statement, A(:) fills A, preserving its shape from before. In this case, the right side must contain the same number of elements as A.
Example
Create a script file and type the following code in it −
A = [1 2 3 4; 4 5 6 7; 7 8 9 10]
A(:,2) % second column of A
A(:,2:3) % second and third column of A
A(2:3,2:3) % second and third rows and second and third columns
When you run the file, it displays the following result −
All variables of all data types in MATLAB are multidimensional arrays. A vector is a one-dimensional array and a matrix is a two-dimensional array.
We have already discussed vectors and matrices. In this chapter, we will discuss multidimensional arrays. However, before that, let us discuss some special types of arrays.
Special Arrays in MATLAB
In this section, we will discuss some functions that create some special arrays. For all these functions, a single argument creates a square array, double arguments create rectangular array.
The zeros() function creates an array of all zeros −
For example −
zeros(5)
MATLAB will execute the above statement and return the following result −
ans =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
The ones() function creates an array of all ones −
For example −
ones(4,3)
MATLAB will execute the above statement and return the following result −
ans =
1 1 1
1 1 1
1 1 1
1 1 1
The eye() function creates an identity matrix.
For example −
eye(4)
MATLAB will execute the above statement and return the following result −
ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
The rand() function creates an array of uniformly distributed random numbers on (0,1) −
For example −
rand(3, 5)
MATLAB will execute the above statement and return the following result −
A magic square is a square that produces the same sum, when its elements are added row-wise, column-wise or diagonally.
The magic() function creates a magic square array. It takes a singular argument that gives the size of the square. The argument must be a scalar greater than or equal to 3.
magic(4)
MATLAB will execute the above statement and return the following result −
ans =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
Multidimensional Arrays
An array having more than two dimensions is called a multidimensional array in MATLAB. Multidimensional arrays in MATLAB are an extension of the normal two-dimensional matrix.
Generally to generate a multidimensional array, we first create a two-dimensional array and extend it.
For example, let’s create a two-dimensional array a.
a = [7 9 5; 6 1 9; 4 3 2]
MATLAB will execute the above statement and return the following result −
a =
7 9 5
6 1 9
4 3 2
The array a is a 3-by-3 array; we can add a third dimension to a, by providing the values like −
a(:, :, 2)= [ 1 2 3; 4 5 6; 7 8 9]
MATLAB will execute the above statement and return the following result −
We can also use the cat() function to build multidimensional arrays. It concatenates a list of arrays along a specified dimension −
Syntax for the cat() function is −
B = cat(dim, A1, A2...)
Where,
B is the new array created
A1, A2, … are the arrays to be concatenated
dim is the dimension along which to concatenate the arrays
Example
Create a script file and type the following code into it −
a = [9 8 7; 6 5 4; 3 2 1];
b = [1 2 3; 4 5 6; 7 8 9];
c = cat(3, a, b, [ 2 3 1; 4 7 8; 3 9 0])
When you run the file, it displays −
c(:,:,1) =
9 8 7
6 5 4
3 2 1
c(:,:,2) =
1 2 3
4 5 6
7 8 9
c(:,:,3) =
2 3 1
4 7 8
3 9 0
Array Functions
MATLAB provides the following functions to sort, rotate, permute, reshape, or shift array contents.
Function
Purpose
length
Length of vector or largest array dimension
ndims
Number of array dimensions
numel
Number of array elements
size
Array dimensions
iscolumn
Determines whether input is column vector
isempty
Determines whether array is empty
ismatrix
Determines whether input is matrix
isrow
Determines whether input is row vector
isscalar
Determines whether input is scalar
isvector
Determines whether input is vector
blkdiag
Constructs block diagonal matrix from input arguments
circshift
Shifts array circularly
ctranspose
Complex conjugate transpose
diag
Diagonal matrices and diagonals of matrix
flipdim
Flips array along specified dimension
fliplr
Flips matrix from left to right
flipud
Flips matrix up to down
ipermute
Inverses permute dimensions of N-D array
permute
Rearranges dimensions of N-D array
repmat
Replicates and tile array
reshape
Reshapes array
rot90
Rotates matrix 90 degrees
shiftdim
Shifts dimensions
issorted
Determines whether set elements are in sorted order
sort
Sorts array elements in ascending or descending order
sortrows
Sorts rows in ascending order
squeeze
Removes singleton dimensions
transpose
Transpose
vectorize
Vectorizes expression
Examples
The following examples illustrate some of the functions mentioned above.
Length, Dimension and Number of elements −
Create a script file and type the following code into it −
x = [7.1, 3.4, 7.2, 28/4, 3.6, 17, 9.4, 8.9];
length(x) % length of x vector
y = rand(3, 4, 5, 2);
ndims(y) % no of dimensions in array y
s = ['Zara', 'Nuha', 'Shamim', 'Riz', 'Shadab'];
numel(s) % no of elements in s
When you run the file, it displays the following result −
ans = 8
ans = 4
ans = 23
Circular Shifting of the Array Elements −
Create a script file and type the following code into it −
a = [1 2 3; 4 5 6; 7 8 9] % the original array a
b = circshift(a,1) % circular shift first dimension values down by 1.
c = circshift(a,[1 -1]) % circular shift first dimension values % down by 1
% and second dimension values to the left % by 1.</code></pre>
When you run the file, it displays the following result −
Create a script file and type the following code into it −
v = [ 23 45 12 9 5 0 19 17] % horizontal vector
sort(v) % sorting v
m = [2 6 4; 5 3 9; 2 0 1] % two dimensional array
sort(m, 1) % sorting m along the row
sort(m, 2) % sorting m along the column
When you run the file, it displays the following result −
MATLAB will execute the above statement and return the following result −
sa =
3 4 5
4 5 6
Deleting a Row or a Column in a Matrix
You can delete an entire row or column of a matrix by assigning an empty set of square braces [] to that row or column. Basically, [] denotes an empty array.
A vector is a one-dimensional array of numbers. MATLAB allows creating two types of vectors −
Row vectors
Column vectors
Row Vectors
Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit the elements.
r = [7 8 9 10 11]
MATLAB will execute the above statement and return the following result −
r =
7 8 9 10 11
Column Vectors
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]
MATLAB will execute the above statement and return the following result −
c =
7
8
9
10
11
Referencing the Elements of a Vector
You can reference one or more of the elements of a vector in several ways. The ith component of a vector v is referred as v(i). For example −
v = [ 1; 2; 3; 4; 5; 6]; % creating a column vector of 6 elements
v(3)
MATLAB will execute the above statement and return the following result −
ans = 3
When you reference a vector with a colon, such as v(:), all the components of the vector are listed.
v = [ 1; 2; 3; 4; 5; 6]; % creating a column vector of 6 elements
v(:)
MATLAB will execute the above statement and return the following result −
ans =
1
2
3
4
5
6
MATLAB allows you to select a range of elements from a vector.
For example, let us create a row vector rv of 9 elements, then we will reference the elements 3 to 7 by writing rv(3:7) and create a new vector named sub_rv.
rv = [1 2 3 4 5 6 7 8 9];
sub_rv = rv(3:7)
MATLAB will execute the above statement and return the following result −
There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially. The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −
MATLAB provides following types of loops to handle looping requirements. Click the following links to check their detail −
Sr.No.
Loop Type & Description
1
while loopRepeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
2
for loopExecutes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
3
nested loopsYou can use one or more loops inside any another loop.
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
MATLAB supports the following control statements. Click the following links to check their detail.
Sr.No.
Control Statement & Description
1
break statementTerminates the loop statement and transfers execution to the statement immediately following the loop.
2
continue statementCauses the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
Decision making structures require that the programmer should specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the programming languages −
MATLAB provides following types of decision making statements. Click the following links to check their detail −
Sr.No.
Statement & Description
1
if … end statementAn if … end statement consists of a boolean expression followed by one or more statements.
2
if…else…end statementAn if statement can be followed by an optional else statement, which executes when the boolean expression is false.
3
If… elseif…elseif…else…end statementsAn if statement can be followed by one (or more) optional elseif… and an else statement, which is very useful to test various conditions.
4
nested if statementsYou can use one if or elseif statement inside another if or elseif statement(s).
5
switch statementA switch statement allows a variable to be tested for equality against a list of values.
6
nested switch statementsYou can use one switch statement inside another switch statement(s).
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. MATLAB is designed to operate primarily on whole matrices and arrays. Therefore, operators in MATLAB work both on scalar and non-scalar data. MATLAB allows the following types of elementary operations −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operations
Set Operations
Arithmetic Operators
MATLAB allows two different types of arithmetic operations −
Matrix arithmetic operations
Array arithmetic operations
Matrix arithmetic operations are same as defined in linear algebra. Array operations are executed element by element, both on one-dimensional and multidimensional array.
The matrix operators and array operators are differentiated by the period (.) symbol. However, as the addition and subtraction operation is same for matrices and arrays, the operator is same for both cases. The following table gives brief description of the operators −
Sr.No.
Operator & Description
1
+Addition or unary plus. A+B adds the values stored in variables A and B. A and B must have the same size, unless one is a scalar. A scalar can be added to a matrix of any size.
2
–Subtraction or unary minus. A-B subtracts the value of B from A. A and B must have the same size, unless one is a scalar. A scalar can be subtracted from a matrix of any size.
3
*Matrix multiplication. C = A*B is the linear algebraic product of the matrices A and B. More precisely,For non-scalar A and B, the number of columns of A must be equal to the number of rows of B. A scalar can multiply a matrix of any size.
4
.*Array multiplication. A.*B is the element-by-element product of the arrays A and B. A and B must have the same size, unless one of them is a scalar.
5
/Slash or matrix right division. B/A is roughly the same as B*inv(A). More precisely, B/A = (A’\B’)’.
6
./Array right division. A./B is the matrix with elements A(i,j)/B(i,j). A and B must have the same size, unless one of them is a scalar.
7
\Backslash or matrix left division. If A is a square matrix, A\B is roughly the same as inv(A)*B, except it is computed in a different way. If A is an n-by-n matrix and B is a column vector with n components, or a matrix with several such columns, then X = A\B is the solution to the equation AX = B. A warning message is displayed if A is badly scaled or nearly singular.
8
.\Array left division. A.\B is the matrix with elements B(i,j)/A(i,j). A and B must have the same size, unless one of them is a scalar.
9
^Matrix power. X^p is X to the power p, if p is a scalar. If p is an integer, the power is computed by repeated squaring. If the integer is negative, X is inverted first. For other values of p, the calculation involves eigenvalues and eigenvectors, such that if [V,D] = eig(X), then X^p = V*D.^p/V.
10
.^Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. A and B must have the same size, unless one of them is a scalar.
11
‘Matrix transpose. A’ is the linear algebraic transpose of A. For complex matrices, this is the complex conjugate transpose.
12
.’Array transpose. A.’ is the array transpose of A. For complex matrices, this does not involve conjugation.
Relational Operators
Relational operators can also work on both scalar and non-scalar data. Relational operators for arrays perform element-by-element comparisons between two arrays and return a logical array of the same size, with elements set to logical 1 (true) where the relation is true and elements set to logical 0 (false) where it is not.
The following table shows the relational operators available in MATLAB −
Sr.No.
Operator & Description
1
<Less than
2
<=Less than or equal to
3
>Greater than
4
>=Greater than or equal to
5
==Equal to
6
~=Not equal to
Logical Operators
MATLAB offers two types of logical operators and functions −
Element-wise − These operators operate on corresponding elements of logical arrays.
Short-circuit − These operators operate on scalar and, logical expressions.
Element-wise logical operators operate element-by-element on logical arrays. The symbols &, |, and ~ are the logical array operators AND, OR, and NOT.
Short-circuit logical operators allow short-circuiting on logical operations. The symbols && and || are the logical short-circuit operators AND and OR.
Bitwise Operations
Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows −
p
q
p & q
p | q
p ^ q
0
0
0
0
0
0
1
0
1
1
1
1
1
1
0
1
0
0
1
1
Assume if A = 60; and B = 13; Now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
—————–
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
MATLAB provides various functions for bit-wise operations like ‘bitwise and’, ‘bitwise or’ and ‘bitwise not’ operations, shift operation, etc.
The following table shows the commonly used bitwise operations −
Function
Purpose
bitand(a, b)
Bit-wise AND of integers a and b
bitcmp(a)
Bit-wise complement of a
bitget(a,pos)
Get bit at specified position pos, in the integer array a
bitor(a, b)
Bit-wise OR of integers a and b
bitset(a, pos)
Set bit at specific location pos of a
bitshift(a, k)
Returns a shifted to the left by k bits, equivalent to multiplying by 2k. Negative values of k correspond to shifting bits right or dividing by 2|k| and rounding to the nearest integer towards negative infinite. Any overflow bits are truncated.
bitxor(a, b)
Bit-wise XOR of integers a and b
swapbytes
Swap byte ordering
Set Operations
MATLAB provides various functions for set operations, like union, intersection and testing for set membership, etc.
The following table shows some commonly used set operations −
Sr.No.
Function & Description
1
intersect(A,B)Set intersection of two arrays; returns the values common to both A and B. The values returned are in sorted order.
2
intersect(A,B,’rows’)Treats each row of A and each row of B as single entities and returns the rows common to both A and B. The rows of the returned matrix are in sorted order.
3
ismember(A,B)Returns an array the same size as A, containing 1 (true) where the elements of A are found in B. Elsewhere, it returns 0 (false).
4
ismember(A,B,’rows’)Treats each row of A and each row of B as single entities and returns a vector containing 1 (true) where the rows of matrix A are also rows of B. Elsewhere, it returns 0 (false).
5
issorted(A)Returns logical 1 (true) if the elements of A are in sorted order and logical 0 (false) otherwise. Input A can be a vector or an N-by-1 or 1-by-N cell array of strings. A is considered to be sorted if A and the output of sort(A) are equal.
6
issorted(A, ‘rows’)Returns logical 1 (true) if the rows of two-dimensional matrix A is in sorted order, and logical 0 (false) otherwise. Matrix A is considered to be sorted if A and the output of sortrows(A) are equal.
7
setdiff(A,B)Sets difference of two arrays; returns the values in A that are not in B. The values in the returned array are in sorted order.
8
setdiff(A,B,’rows’)Treats each row of A and each row of B as single entities and returns the rows from A that are not in B. The rows of the returned matrix are in sorted order.The ‘rows’ option does not support cell arrays.
MATLAB does not require any type declaration or dimension statements. Whenever MATLAB encounters a new variable name, it creates the variable and allocates appropriate memory space.
If the variable already exists, then MATLAB replaces the original content with new content and allocates new storage space, where necessary.
For example,
Total = 42
The above statement creates a 1-by-1 matrix named ‘Total’ and stores the value 42 in it.
Data Types Available in MATLAB
MATLAB provides 15 fundamental data types. Every data type stores data that is in the form of a matrix or array. The size of this matrix or array is a minimum of 0-by-0 and this can grow up to a matrix or array of any size.
The following table shows the most commonly used data types in MATLAB −
Sr.No.
Data Type & Description
1
int88-bit signed integer
2
uint88-bit unsigned integer
3
int1616-bit signed integer
4
uint1616-bit unsigned integer
5
int3232-bit signed integer
6
uint3232-bit unsigned integer
7
int6464-bit signed integer
8
uint6464-bit unsigned integer
9
singlesingle precision numerical data
10
doubledouble precision numerical data
11
logicallogical values of 1 or 0, represent true and false respectively
12
charcharacter data (strings are stored as vector of characters)
13
cell arrayarray of indexed cells, each capable of storing an array of a different dimension and data type
14
structureC-like structures, each structure having named fields capable of storing an array of a different dimension and data type
15
function handlepointer to a function
16
user classesobjects constructed from a user-defined class
17
java classesobjects constructed from a Java class
Example
Create a script file with the following code −
str = 'Hello World!'
n = 2345
d = double(n)
un = uint32(789.50)
rn = 5678.92347
c = int32(rn)
When the above code is compiled and executed, it produces the following result −
str = Hello World!
n = 2345
d = 2345
un = 790
rn = 5678.9
c = 5679
Data Type Conversion
MATLAB provides various functions for converting, a value from one data type to another. The following table shows the data type conversion functions −
Function
Purpose
char
Convert to character array (string)
int2str
Convert integer data to string
mat2str
Convert matrix to string
num2str
Convert number to string
str2double
Convert string to double-precision value
str2num
Convert string to number
native2unicode
Convert numeric bytes to Unicode characters
unicode2native
Convert Unicode characters to numeric bytes
base2dec
Convert base N number string to decimal number
bin2dec
Convert binary number string to decimal number
dec2base
Convert decimal to base N number in string
dec2bin
Convert decimal to binary number in string
dec2hex
Convert decimal to hexadecimal number in string
hex2dec
Convert hexadecimal number string to decimal number
hex2num
Convert hexadecimal number string to double-precision number
num2hex
Convert singles and doubles to IEEE hexadecimal strings
cell2mat
Convert cell array to numeric array
cell2struct
Convert cell array to structure array
cellstr
Create cell array of strings from character array
mat2cell
Convert array to cell array with potentially different sized cells
num2cell
Convert array to cell array with consistently sized cells
struct2cell
Convert structure to cell array
Determination of Data Types
MATLAB provides various functions for identifying data type of a variable.
Following table provides the functions for determining the data type of a variable −
Function
Purpose
is
Detect state
isa
Determine if input is object of specified class
iscell
Determine whether input is cell array
iscellstr
Determine whether input is cell array of strings
ischar
Determine whether item is character array
isfield
Determine whether input is structure array field
isfloat
Determine if input is floating-point array
ishghandle
True for Handle Graphics object handles
isinteger
Determine if input is integer array
isjava
Determine if input is Java object
islogical
Determine if input is logical array
isnumeric
Determine if input is numeric array
isobject
Determine if input is MATLAB object
isreal
Check if input is real array
isscalar
Determine whether input is scalar
isstr
Determine whether input is character array
isstruct
Determine whether input is structure array
isvector
Determine whether input is vector
class
Determine class of object
validateattributes
Check validity of array
whos
List variables in workspace, with sizes and types
Example
Create a script file with the following code −
x = 3
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
x = 23.54
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
x = [1 2 3]
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
x = 'Hello'
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
When you run the file, it produces the following result −
x = 3
ans = 0
ans = 1
ans = 1
ans = 1
ans = 1
x = 23.540
ans = 0
ans = 1
ans = 1
ans = 1
ans = 1
x =
1 2 3
ans = 0
ans = 1
ans = 1
ans = 0
x = Hello
ans = 0
ans = 0
ans = 1
ans = 0
ans = 0
So far, we have used MATLAB environment as a calculator. However, MATLAB is also a powerful programming language, as well as an interactive computational environment.
In previous chapters, you have learned how to enter commands from the MATLAB command prompt. MATLAB also allows you to write series of commands into a file and execute the file as complete unit, like writing a function and calling it.
The M Files
MATLAB allows writing two kinds of program files −
Scripts − script files are program files with .m extension. In these files, you write series of commands, which you want to execute together. Scripts do not accept inputs and do not return any outputs. They operate on data in the workspace.
Functions − functions files are also program files with .m extension. Functions can accept inputs and return outputs. Internal variables are local to the function.
You can use the MATLAB editor or any other text editor to create your .mfiles. In this section, we will discuss the script files. A script file contains multiple sequential lines of MATLAB commands and function calls. You can run a script by typing its name at the command line.
Creating and Running Script File
To create scripts files, you need to use a text editor. You can open the MATLAB editor in two ways −
Using the command prompt
Using the IDE
If you are using the command prompt, type edit in the command prompt. This will open the editor. You can directly type edit and then the filename (with .m extension)
edit
Or
edit <filename>
The above command will create the file in default MATLAB directory. If you want to store all program files in a specific folder, then you will have to provide the entire path.
Let us create a folder named progs. Type the following commands at the command prompt (>>) −
mkdir progs % create directory progs under default directory
chdir progs % changing the current directory to progs
edit prog1.m % creating an m file named prog1.m
If you are creating the file for first time, MATLAB prompts you to confirm it. Click Yes.
Alternatively, if you are using the IDE, choose NEW -> Script. This also opens the editor and creates a file named Untitled. You can name and save the file after typing the code.
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 −
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).
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
cd
Changes current directory.
date
Displays current date.
delete
Deletes a file.
diary
Switches on/off diary file recording.
dir
Lists all files in current directory.
load
Loads workspace variables from a file.
path
Displays search path.
pwd
Displays current directory.
save
Saves workspace variables in a file.
type
Displays contents of a file.
what
Lists all MATLAB files in the current directory.
wklread
Reads .wk1 spreadsheet file.
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.
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.
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.
Vector, Matrix and Array Commands
The following table shows various commands used for working with arrays, matrices and vectors −
Command
Purpose
cat
Concatenates arrays.
find
Finds indices of nonzero elements.
length
Computes number of elements.
linspace
Creates regularly spaced vector.
logspace
Creates logarithmically spaced vector.
max
Returns largest element.
min
Returns smallest element.
prod
Product of each column.
reshape
Changes size.
size
Computes array size.
sort
Sorts each column.
sum
Sums each column.
eye
Creates an identity matrix.
ones
Creates an array of ones.
zeros
Creates an array of zeros.
cross
Computes matrix cross products.
dot
Computes matrix dot products.
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.
Plotting Commands
MATLAB provides numerous commands for plotting graphs. The following table shows some of the commonly used commands for plotting −