Unit 1 Matlab
Unit 1 Matlab
VARIABLE:
Create and Edit Variables
Create Variables:
The MATLAB® workspace consists of the variables you create and store in memory during a
MATLAB session. You can create new variables in the workspace by running MATLAB code
or using existing variables.
To create a new variable, enter the variable name in the Command Window, followed by an
equal sign (=) and the value you want to assign to the variable. For example, if you run these
statements, MATLAB adds the four variables x, A, I, and C to the workspace:
x = 5.71;
A = [1 2 3; 4 5 6; 7 8 9];
I = besseli(x,A);
C = {A A A};
Main Content
Create and Edit Variables
Create Variables
The MATLAB® workspace consists of the variables you create and store in memory during a
MATLAB session. You can create new variables in the workspace by running MATLAB code
or using existing variables.
To create a new variable, enter the variable name in the Command Window, followed by an
equal sign (=) and the value you want to assign to the variable. For example, if you run these
statements, MATLAB adds the four variables x, A, I, and C to the workspace:
x = 5.71;
A = [1 2 3; 4 5 6; 7 8 9];
I = besseli(x,A);
C = {A A A};
Workspace browser showing all four variables
If you do not end the assignment statement with a semicolon (;), MATLAB displays the result
in the Command Window. For example,
x = 5.71
x=
5.7100
If you do not explicitly assign the output of a statement to a variable, MATLAB generally
assigns the result to the reserved word ans. The value of ans changes with every statement
that returns an output value that is not assigned to a variable. For example,
sin(1)
ans =
0.8415
To view and edit variables, use the Workspace browser and Variables .
Matlab Variables
Introduction to Matlab Variables
The variables created in MATLAB code are managed by its workspace, which is responsible
for handling memory locations and storing the values assigned to each respective variable.
Matlab workspace supports creating new variables and reusing existing variables in
command execution. In the Matlab environment, each variable is treated as a matrix or an
array, irrespective of their data types.
var1 = 15.41
var2 = [10 22 43; 40 45 63; 27 48 19]
Output:
Matlab Variables1
2. Assigning an expression to a variable
Code:
var1 = sqrt(16)
var2=sin(1)
Output:
Matlab Variables2
3. Initializing variables in Matlab
Matlab variables support both empty and non-empty data as initial values.
Code:
var1 = [] var2=10
Output:
Matlab Variables3How do Variables work in Matlab?
Matlab adds the variables to the workspace once a variable is created from the code.
Code:
var1="I am variable";
I = [1 2 3; 4 5 6; 7 8 9];
Output:
Matlab Variables4
Explanation: The content of the variable can be edited using a command or can be edited
from the variable editor. Other operations, such as deleting, duplicating, copying, resizing, or
reshaping the variable, can be done in the workspace.
Code:
var1=50;var2=60;var3=70;
Output:
1. Char
Matlab variables support the array of characters.
Code:
2.Complex
The complex variables i.e. in the form of “real +i*imaginary” are supported by Matlab
variables.
Code:
complex_var = complex(5,10);
Output:
Complex
5 + 10i
b. Creating an array of complex numbers:
Code:
real = uint8([11;25;23;40]);
imgainary = uint8([21;25;27;47]);
complex_arr = complex(real,imgainary)
Output:
Complex_arr =
11 + 21i
25 + 25i
23 + 27i
40 + 47i
3. Double
In Matlab, the default numeric data type or class is ‘double’, which provides high precision
for most of the computational tasks. Numeric variables are automatically captured in the
form of 64-bit (8-byte) double-precision floating-point values.
Code:
var_name = 100;
xtype = class(var_name)
Output:
xtype = double
NUMBERS:
Numeric Types :
Integer and floating-point data
Numeric classes in MATLAB® include signed and unsigned integers, and single-precision
and double-precision floating-point numbers. By default, MATLAB stores all numeric values
as double-precision floating point. (You cannot change the default type and precision.) You
can choose to store any number, or array of numbers, as integers or as single-precision.
Integer and single precision arrays offer more memory-efficient storage than double
precision.
All numeric types support basic array operations, such as indexing, reshaping, and
mathematical operations.
Center
Documentation Home
MATLAB
Language Fundamentals
Data Types
Category
Numeric Types
Characters and Strings
Dates and Time
Categorical Arrays
Tables
Timetables
Structures
Cell Arrays
Function Handles
Dictionaries
Time Series
Data Type Identification
Data Type Conversion
Main Content
Numeric Types
Integer and floating-point data
Numeric classes in MATLAB® include signed and unsigned integers, and single-precision
and double-precision floating-point numbers. By default, MATLAB stores all numeric values
as double-precision floating point. (You cannot change the default type and precision.) You
can choose to store any number, or array of numbers, as integers or as single-precision.
Integer and single precision arrays offer more memory-efficient storage than double
precision.
All numeric types support basic array operations, such as indexing, reshaping, and
mathematical operations.
Topics
Floating-Point Numbers
MATLAB represents floating-point numbers in either double-precision or single-precision
format. The default is double precision.
Integers
MATLAB supports 1-, 2-, 4-, and 8-byte storage for integer data. If you use the smallest
integer type that accommodates your data, you can save memory and program execution
time.
Integer Arithmetic
This example shows how to perform arithmetic on integer data representing signals and
images.
Empty Matrices
If you construct a matrix using empty matrix elements, the empty matrices are ignored in the
resulting matrix.
Concatenation Examples
These examples show how to concatenate different data types.
Matlab operators :
An operator is a symbol that tells the compiler to perform various numerical or logical
manipulations. MATLAB is designed to operate mainly on whole matrices and arrays.
Therefore, functions in MATLAB work both on scalar and non-scalar data.
MATLAB has several types of operators, symbols, and special characters to deal with
variables, functions, and arithmetic operations.
Except for some matrix operators, MATLAB arithmetic operators work on corresponding
functions of arrays with equal dimensions. For vectors and rectangular array, both operands
must be the equivalent size unless one is a scalar. If one operand is a scalar and the other is
not, MATLAB applies the scalar to every item of the other operand, this property is called
scalar expansion.
This example uses scalar expansion to evaluate the product of a scalar operand and a
matrix.
A = magic (3)
A=
8 1 6
3 5 7
4 9 2
3*A
ans=
24 3 18
9 15 21
12 27 6
A = [2 7 6; 9 0 5; 3 0.5 6];
B = [8 7 0; 3 2 5; 4 -1 7];
A == B
ans =
0 1 0
0 0 1
0 0 0
For vectors and rectangular array, both operands must be the same size unless one is a
scalar. In this case, where one operand is a scalar, and the other is not, MATLAB tests the
scalar against every element of the other operand. Locations where the particular relation is
true receive logical
1. Locations where the relation is false receive logical 0.
The values returned by MATLAB logical operators and functions, with the exception of
bit-wise functions, are of type logical and are suitable for use with logical indexing.
Bit-Wise Operator:
The following functions execute bit-wise logical operations on nonnegative integer inputs.
Inputs may be scalar or in arrays. If in arrays, these operations produce a like-sized output
array.
The examples are present in the following table use scalar inputs A and B, where
Short-Circuit Operators:
The following operators execute AND and OR operations on logical expressions, including
scalar values. They are short-circuiting operators in that they calculate their second operand
only when the first operand does not fully determine the output.
Expressions:
Why Use Expressions
An expression used in a class definition can be any valid MATLAB® statement that
evaluates to a single array. Use expressions to define property default values and in attribute
specifications. Expressions are useful to derive values in terms of other values. For example,
suppose that you want to define a constant property with the full precision value of 2π. You
can assign the property the value returned by the expression 2*pi. MATLAB evaluates the
function when first loading the class.
For information on assigning property default values and attribute values, see Initialize
Property Values and Property Attributes.
MATLAB Expressions
1.String Evaluation
2.Shell Escape Functions
String Evaluation:
String evaluation adds power and flexibility to the MATLAB language, letting you perform
operations like executing user-supplied strings and constructing executable strings through
concatenation of strings stored in variables.
eval:
The eval function evaluates a string that contains a MATLAB expression, statement, or
function call. In its simplest form, the eval syntax is
eval('string')
For example, this code uses eval on an expression to generate a Hilbert matrix of order n.
t = '1/(m + n - 1)';
for m = 1:k
for n = 1:k
a(m,n) = eval(t);
end
end
Here is an example that uses eval on a statement.
eval('t = clock');
Constructing Strings for Evaluation. You can concatenate strings to create a complete
expression for input to eval. This code shows how eval can create 10 variables named P1,
P2, ..., P10, and set each of them to a different value.
for n = 1:10
eval(['P', int2str(n), '= n .^ 2'])
end
feval:
The feval function differs from eval in that it executes a function rather than a MATLAB
expression. The function to be executed is specified in the first argument by either a function
handle or a string containing the function name.
You can use feval and the input function to choose one of several tasks defined by M-files.
This example uses function handles for the sin, cos, and log functions.
The major uses of Matlab vectors are to create x-y plots which cannot be represented using
linear algebra. Thus, vectors become a convenient data structure. It enforces the rules of
linear algebra in its operations. Therefore it is important to keep an eye out for detail for
vector creation and manipulation.
Row Vector
Column Vector
Row Vector
As the name suggests, it is a horizontal set of elements represented within square brackets.
The elements within the square brackets are then separated by a space or comma.
X = [ 5 6 9 ] or X = [ 5 , 6 , 9 ]
Column Vector
A column vector represents a vertical set of elements represented within square brackets.
One can write a column vector in two ways. The first way is to separate each element by a
semicolon. The second way is to write each element on the next row in the command
window.
X = [ 7 ; 5 ; 9 ] or
X=[7
5
9]
The first way is to build it using the zeroes of the built-in function, linspace, and logspace.
You can assign mathematical expressions involving vectors.
Vectors can also be created by appending elements to a scalar.
Vector created using colon notation.
Let us look at some of the methods which are more widely used than the others.
Creating vectors with ones, zeros, linspace, and logspace: Creating vectors with these
factors allows users to make vectors with prescribed spacing between the elements and a
specific size.
One has to decide how long the vector has to be to create a vector with one of these
functions. Once that is decided, one has to decide if the vector is a row or column vector.
There are two arguments for the ones and zeros functions. The first is how many rows you
want to have in your matrix. The number of columns is the second. Set the relevant
argument of ones and zeros to one to generate a row or a column vector.
For example, to create a row vector of length 6, filled with ones, use:
>> x = ones(1,6)
>> y = zeros(6,1)
Vectors with linearly or logarithmically spaced elements are produced by the linspace and
logspace functions. Here are some illustrations with MATLAB output.
>> x = linspace(1,5,5)
x=
1 2 3 4 5
>> y = logspace(1,4,4)
y=
Both linspace and logspace include an optional third argument. The third argument specifies
the number of elements to use inside the first and second argument range.
If you're working in three dimensions, define the vectors as column vectors with x, y, and z
components and store them in a matrix. You may create three vectors, for instance, if their
components are (1, 2, 3), (2, 3, 1), and (3, 1, 2) as follows:
vectors = [1 2 3; 2 3 1; 3 1 2];
Create column vectors to represent the vectors' beginning positions and store them in a
matrix. For example, if you want to start the first vector at the origin and the other two
vectors at points (1, 1, 1) and (2, 2, 2), respectively, you can define them as follows:
startpoints = [0 0 0; 1 1 1; 2 2 2];
Use the quiver function to plot the vectors. The basic syntax of the quiver function is:
quiver(x, y, u, v, scale)
Where x and y are the coordinates of the starting points of the vectors, u and v are the
components of the vectors, and scale is an optional scaling factor that controls the length of
the vectors.
To plot the vectors defined in step 1 and 2, you can use the following code:
Note that if you are working in 3D, you need to include the z components of the vectors and
the starting points in the quiver function as well.
Customize the plot as needed. You can change the color and width of the vectors, add labels
and a title, adjust the scaling, and so on. Here are some examples:
xlabel('X');
ylabel('Y');
title('Vector Plot');
These basic steps are to plot vectors in MATLAB using the quiver function. You can also use
other functions, such as an arrow and compass.
Array Creation
To create an array with four elements in a single row, separate the elements with either a
comma (,) or a space.
a = [1 2 3 4]
a = 1×4
1 2 3 4
To create a matrix that has multiple rows, separate the rows with semicolons.
a = [1 3 5; 2 4 6; 7 8 10]
a = 3×3
1 3 5
2 4 6
7 8 10
Another way to create a matrix is to use a function, such as ones, zeros, or rand. For
example, create a 5-by-1 column vector of zeros.
z = zeros(5,1)
z = 5×1
0
0
0
0
0
Matrix and Array Operations
MATLAB allows you to process all of the values in a matrix using a single arithmetic operator
or function.
a + 10
ans = 3×3
11 13 15
12 14 16
17 18 20
sin(a)
ans = 3×3
a'
ans = 3×3
1 2 7
3 4 8
5 6 10
You can perform standard matrix multiplication, which computes the inner products between
rows and columns, using the * operator. For example, confirm that a matrix times its inverse
returns the identity matrix:
p = a*inv(a)
p = 3×3
Notice that p is not a matrix of integer values. MATLAB stores numbers as floating-point
values, and arithmetic operations are sensitive to small differences between the actual value
and its floating-point representation.
DOT PRODUCT :
Syntax
C = dot(A,B)
C = dot(A,B,dim)
Description
example
C = dot(A,B) returns the scalar dot product of A and B.
If A and B are vectors, then they must have the same length.
If A and B are matrices or multidimensional arrays, then they must have the same size. In
this case, the dot function treats A and B as collections of vectors. The function calculates
the dot product of corresponding vectors along the first array dimension whose size does not
equal 1.
example
C = dot(A,B,dim) evaluates the dot product of A and B along dimension, dim. The dim input
is a positive integer scalar.
Examples
collapse all
Dot Product of Real Vectors
Create two simple, three-element vectors.
A = [4 -1 2];
B = [2 -2 -1];
Calculate the dot product of A and B.
C = dot(A,B)
C=8
The result is 8 since
Division
Dividing every element by a single value is accomplished just using the / for division.
[5 6 7] / 10
ans =
.5000 .6000 .7000
Dividing every element in an array by a value in a corresponding array is done using the ./
(dot slash) notation.
[5 6 7] ./ [ 8 9 10 ]
ans =
0.6250 0.6667 0.7000
[5 6 7] / [ 8 9 10 ]
ans =
0.6694
Multiplication
Multiplying every element by a single value is accomplished just using the *.
[5 6 7] * 10
ans =
50 60 70
Multiplying every element in an array by a value in a corresponding array is done using the .*
(dot slash) notation.
[5 6 7] .* [ 8 9 10 ]
ans =
40 54 70
Other Operations
Power (^) and other operators generally work in a similar method. See the online Matlab
help.
Colon Operator
As stated elsewhere, the colon is used to build a list of values (an array) based on a "start
value" : "increment value" : "end value"
If an "increment value" is not given, then 1 is assumed.
Categories
File Operations:
Find, view, and change files and folders.
Cloud File Storage:
Securely store and share files between the desktop, mobile, and MATLAB Online™
applications.
Search Path:
View and change MATLAB search path
File Compression:
Zip and tar files; file compression and decompression.
File Name Construction:
Components of full paths, including folders, extensions, and separators.
Working with files :scripts
The simplest type of MATLAB® program is called a script. A script is a file that contains
multiple sequential lines of MATLAB commands and function calls. You can run a script by
typing its name at the command line.
Scripts
To create a script, use the edit command,
edit mysphere
This command opens a blank file named mysphere.m. Enter some code that creates a unit
sphere, doubles the radius, and plots the results:
[x,y,z] = sphere;
r = 2;
surf(x*r,y*r,z*r)
axis equal
Next, add code that calculates the surface area and volume of a sphere:
A = 4*pi*r^2;
V = (4/3)*pi*r^3;
Whenever you write code, it is a good practice to add comments that describe the code.
Comments enable others to understand your code and can refresh your memory when you
return to it later. Add comments using the percent (%) symbol.
mysphere
You can also run scripts from the Editor using the Run button, .
Live Scripts
Instead of writing code and comments in plain text, you can use formatting options in live
scripts to enhance your code. Live scripts allow you to view and interact with both code and
output and can include formatted text, equations, and images.
For example, convert mysphere to a live script by selecting Save As and changing the file
type to a MATLAB live code file (*.mlx). Then, replace the code comments with formatted
text. For instance:
Convert the comment lines to text. Select each line that begins with a percent symbol, and
then select Text, . Remove the percent symbols.
Rewrite the text to replace the comments at the end of code lines. To apply a monospace
font to function names in the text, select M. To add an equation, select Equation on the Insert
tab.
Text and font options are in the Text section of the Live Editor tab.
To create a new live script using the edit command, include the .mlx extension with the file
name:
edit newfile.mlx
You can call the function from the command line, using the same syntax rules that apply to
functions installed with MATLAB. For instances, calculate the factorial of 5.
x = 5;
y = fact(5)
y=
120
Starting in R2016b, another option for storing functions is to include them at the end of a
script file. For instance, create a file named mystats.m with a few commands and two
functions, fact and perm. The script calculates the permutation of (3,2).
x = 3;
y = 2;
z = perm(x,y)
function p = perm(n,r)
p = fact(n)/fact(n-r);
end
function f = fact(n)
f = prod(1:n);
end
Call the script from the command line.
mystats
z=
6
Syntax for Function Definition:
The first line of every function is the definition statement, which includes the following
elements.
function myFunction(x)
Or you can use empty square brackets.
function [] = myFunction(x)
Function name (required)
Valid function names follow the same rules as variable names. They must start with a letter,
and can contain letters, digits, or underscores.
Note:
To avoid confusion, use the same name for both the function file and the first function within
the file. MATLAB associates your program with the file name, not the function name. Script
files cannot have the same name as a function in the file.
If your function accepts any inputs, enclose their names in parentheses after the function
name. Separate inputs with commas.
function y = myFunction(one,two,three)
If there are no inputs, you can omit the parentheses.
Tip:
When you define a function with multiple input or output arguments, list any required
arguments first. This ordering allows you to call your function without specifying optional
arguments.
Program files can contain multiple functions. If the file contains only function definitions, the
first function is the main function, and is the function that MATLAB associates with the file
name. Functions that follow the main function or script code are called local functions. Local
functions are only available within the file.
End Statements:
Functions end with either an end statement, the end of the file, or the definition line for a
local function, whichever comes first. The end statement is required if:
Any function in the file contains a nested function (a function completely contained within its
parent).
The function is a local function within a function file, and any local function in the file uses the
end keyword.