Matlab Basic
Matlab Basic
Matlab Basic
KEY FEATURES
Built-in graphics for visualizing data and tools for creating custom plots
USES OF MATLAB
1. Signal Processing
2. Communications
3. Image processing
4. Video processing
5. Control systems
6. Test and measurement
7. Computational finance
8. Computational biology.
9. In industry (More than a million engineers and scientists)
10. Academic use(More than 10000 Universities around the word)
Desktop Basics
When you start MATLAB, the desktop appears in its default layout.
The desktop includes these panels:
Command History View or rerun commands that you entered at the command
line.
As you work in MATLAB, you issue commands that create variables and call functions.
For example, create a variable named a by typing this statement at the command line:
a = 1
MATLAB adds variable a to the workspace and displays the result in the Command
Window.
a =
1
When you do not specify an output variable, MATLAB uses the variable ans, short for
answer, to store the results of your calculation.
sin(a)
ans =
0.8415
If you end a statement with a semicolon, MATLAB performs the computation, but
suppresses the display of output in the Command Window.
e = a*b;
You can recall previous commands by pressing the up- and down-arrow keys, and .
Press the arrow keys either at an empty command line or after you type the first few
characters of a command. For example, to recall the command b = 2, type b, and then
press the up-arrow key.
R2012b
MATLAB
Language Fundamentals
Entering Commands
Search R2012
Search
format
Set display format for output
Syntax
format example
Description
example
sets the display of floating-point numeric values to the default display format,
which is the short fixed decimal format. This format displays 5-digit scaled, fixed-point
values.
format
The format function affects only how numbers display in the Command Window, not
how MATLAB computes or saves them.
example
format Style
Examples
collapse all
Change the display format to hexadecimal, and then display the same values.
format hex
intmax('uint64')
ans =
ffffffffffffffff
realmax
ans =
7fefffffffffffff
The hexadecimal display corresponds to the internal representation of the value. It is not
the same as the hexadecimal notation in the C programming language.
Create variable A and increase its value by a multiple of 10 each time through a for loop.
Display each value of A.
A = 5.123456789;
for k=1:10
disp(A)
A = A * 10;
end
5.1235e+000
51.2346e+000
512.3457e+000
5.1235e+003
51.2346e+003
512.3457e+003
5.1235e+006
51.2346e+006
512.3457e+006
5.1235e+009
The values for A display with 4 digits after the decimal point, and an exponent that is a
multiple of 3.
Set the display format to longEng and view the same values of A.
format longEng
A = 5.123456789;
for k=1:10
disp(A)
A = A * 10;
end
5.12345678900000e+000
51.2345678900000e+000
512.345678900000e+000
5.12345678900000e+003
51.2345678900000e+003
512.345678900000e+003
5.12345678900000e+006
51.2345678900000e+006
512.345678900000e+006
5.12345678900000e+009
The values for A display with 15 digits, and an exponent that is a multiple of 3.
9.8769
56
255
9.8769e+09
Input Arguments
collapse all
Style
Output display format, specified as one of the strings listed in the tables that follow.
Use these styles to switch between different output display formats for floating-point
variables. Styles are case insensitive. You also can insert a space between short or long
and the presentation type, for instance, format short E.
Style
short
(defa
ult)
long
short
E
longE
Result
Example
Short fixed decimal format, with 4 digits after the decimal point.
If you are displaying a matrix with a wide range of values, consider using
shortG. See Display Large Data Range in short and shortg Formats
3.1416
Long fixed decimal format, with 15 digits after the decimal point for double 3.14159
2653589
values, and 7 digits after the decimal point for single values.
793
Short scientific notation, with 4 digits after the decimal point.
Integer-valued floating-point numbers with a maximum of 9 digits do not
display in scientific notation.
Long scientific notation, with 15 digits after the decimal point for double
values, and 7 digits after the decimal point for single values.
Integer-valued floating-point numbers with a maximum of 9 digits do not
display in scientific notation.
3.1416e
+00
3.14159
2653589
793e+00
short
G
The more compact of short fixed decimal or scientific notation, with 5 digits. 3.1416
longG
The more compact of long fixed decimal or scientific notation, with 15 digits 3.14159
2653589
for double values, and 7 digits for single values.
79
short
Eng
Short engineering notation, with 4 digits after the decimal point, and an
exponent that is a multiple of 3.
longE
Long engineering notation, with 15 significant digits, and an exponent that is 3.14159
3.1416e
+000
2653589
79e+000
a multiple of 3.
ng
Use these format styles to switch between different output display formats for all numeric
variables.
St
yle
Result
Example
ba
nk
3.14
he
x
400921f
b54442d
18
ra
t
355/113
Use these format styles to affect the spacing in the display of all variables.
DispT
ype
compa
ct
Result
Exampl
e
Suppresses excess line feeds to show more output in a single screen. Contrast
with loose.
theta
= pi/2
theta
=
1.5708
theta
= pi/2
loose
theta
=
1.5708
More About
expand all
Tips
The specified format applies only to the current MATLAB session. To maintain a
format across sessions, choose a Numeric format or Numeric display option in
the Command Window Preferences.
get(0,'Format')
Algorithms
MATLAB always displays integer variables to the appropriate number of digits for the
class. For example, MATLAB uses 3 digits to display numbers of type int8 (for
example, -128:127). Setting format to short or long does not affect the display of
integer variables.
If the largest element of a matrix is larger than 103 or smaller than 10-3, then MATLAB
applies a common scale factor for the short and long formats.
What is an m-file?
What is an m-file?
An m-file, or script file, is a simple text file where you can place MATLAB commands. When the file is run,
MATLAB reads the commands and executes them exactly as it would if you had typed each command
sequentially at the MATLAB prompt. All m-file names must end with the extension '.m' (e.g. test.m). If you
create a new m-file with the same name as an existing m-file, MATLAB will choose the one which appears
first in the path order (type help path in the command window for more information). To make life easier,
choose a name for your m-file which doesn't already exist. To see if a filename.m already exists, type
help filename at the MATLAB prompt.
For simple problems, entering your requests at the MATLAB prompt is fast and efficient. However, as the
number of commands increases or trial and error is done by changing certain variables or values, typing the
commands over and over at the MATLAB prompt becomes tedious. M-files will be helpful and almost
necessary in these cases.
After the m-file is saved with the name filename.m in the current MATLAB folder or directory, you can
execute the commands in the m-file by simply typing filename at the MATLAB command window prompt.
Program files can be scripts that simply execute a series of MATLAB statements, or they
can be functions that also accept input arguments and produce output. Both scripts and
functions contain MATLAB code, and both are stored in text files with a .m extension.
However, functions are more flexible and more easily extensible.
For example, create a script in a file named triarea.m that computes the area of a
triangle:
b = 5;
h = 3;
a = 0.5*(b.* h)
After you save the file, you can call the script from the command line:
triarea
a =
7.5000
To calculate the area of another triangle using the same script, you could update the
values of b and h in the script and rerun it. Each time you run it, the script stores the
result in a variable named a that is in the base workspace.
However, instead of manually updating the script each time, you can make your program
more flexible by converting it to a function. Replace the statements that assign values to b
and h with a function declaration statement. The declaration includes the function
keyword, the names of input and output arguments, and the name of the function.
function a = triarea(b,h)
a = 0.5*(b.* h);
After you save the file, you can call the function with different base and height values
from the command line without modifying the script:
a1
a2
a3
a1
= triarea(1,5)
= triarea(2,10)
= triarea(3,6)
=
2.5000
a2 =
10
a3 =
9
Functions have their own workspace, separate from the base workspace. Therefore, none
of the calls to the function triarea overwrite the value of a in the base workspace.
Instead, the function assigns the results to variables a1, a2, and a3.
The base workspace stores variables that you create at the command line. This includes
any variables that scripts create, assuming that you run the script from the command line
or from the Editor. Variables in the base workspace exist until you clear them or end your
MATLAB session.
Functions do not use the base workspace. Every function has its own function workspace.
Each function workspace is separate from the base workspace and all other workspaces to
protect the integrity of the data. Even local functions in a common file have their own
workspaces. Variables specific to a function workspace are called local variables.
Typically, local variables do not remain in memory from one function call to the next.
When you call a script from a function, the script uses the function workspace.
Like local functions, nested functions have their own workspaces. However, these
workspaces are unique in two significant ways:
Nested functions can access and modify variables in the workspaces of the
functions that contain them.
All of the variables in nested functions or the functions that contain them must be
explicitly defined. That is, you cannot call a function or script that assigns values
to variables unless those variables already exist in the function workspace.
function
Declare function name, inputs, and outputs
Syntax
Description
example
function [y1,...,yN] = myfun(x1,...,xM) declares a function named myfun that
accepts inputs x1,...,xM and returns outputs y1,...,yN. This declaration statement
Examples
expand all
Function avg is a local function. Local functions are only available to other functions
within the same file.
Call function stat2 from the command line.
values = [12.7, 45.4, 98.9, 26.6, 53.1];
[ave,stdev] = stat2(values)
ave =
47.3400
stdev =
29.4124
More About
Local Functions
Nested Functions
Local Functions
This topic explains the term local function, and shows how to create and use local
functions.
MATLAB program files can contain code for more than one function. The first function
in the file (the main function) is visible to functions in other files, or you can call it from
the command line. Additional functions within the file are called local functions. Local
functions are only visible to other functions in the same file. They are equivalent to
subroutines in other programming languages, and are sometimes called subfunctions.
Local functions can occur in any order, as long as the main function appears first. Each
function begins with its own function definition line.
For example, create a program file named mystats.m that contains a main function,
mystats, and two local functions, mymean and mymedian.
function [avg, med] = mystats(x)
n = length(x);
avg = mymean(x,n);
med = mymedian(x,n);
end
function a = mymean(v,n)
% MYMEAN Example of a local function.
a = sum(v)/n;
end
function m = mymedian(v,n)
% MYMEDIAN Another example of a local function.
w = sort(v);
if rem(n,2) == 1
m = w((n + 1)/2);
else
m = (w(n/2) + w(n/2 + 1))/2;
end
end
The local functions mymean and mymedian calculate the average and median of the input
list. The main function mystats determines the length of the list n and passes it to the
local functions.
Although you cannot call a local function from the command line or from functions in
other files, you can access its help using the help function. Specify names of both the
main function and the local function, separating them with a > character:
help mystats>mymean
mymean Example of a local function.
Local functions in the current file have precedence over functions in other files. That is,
when you call a function within a program file, MATLAB checks whether the function is
a local function before looking for other main functions. This allows you to create an
alternate version of a particular function while retaining the original in another file.
All functions, including local functions, have their own workspaces that are separate from
the base workspace. Local functions cannot access variables used by other functions
unless you pass them as arguments. In contrast, nested functions (functions completely
contained within another function) can access variables used by the functions that contain
them.
Search R2012
R2012b
MATLAB
Functions
Function Basics
Search
Nested Functions
On this page
The primary difference between nested functions and other types of functions is that they
can access and modify variables that are defined in their parent functions. As a result:
Nested functions can use variables that are not explicitly passed as input
arguments.
In a parent function, you can create a handle to a nested function that contains the
data necessary to run the nested function.
You cannot define a nested function inside any of the MATLAB program control
statements, such as if/elseif/else, switch/case, for, while, or try/catch.
You must call a nested function either directly by name (without using feval), or
using a function handle that you created using the @ operator (and not str2func).
All of the variables in nested functions or the functions that contain them must be
explicitly defined. That is, you cannot call a function or script that assigns values
to variables unless those variables already exist in the function workspace. (For
more information, see Variables in Nested and Anonymous Functions.)
function main2
nestfun2;
function nestfun2
x = 5;
end
x = x + 1;
end
When parent functions do not use a given variable, the variable remains local to the
nested function. For example, in this function named main, the two nested functions have
their own versions of x that cannot interact with each other:
function main
nestedfun1;
nestedfun2;
function nestedfun1
x = 1;
end
function nestedfun2
x = 2;
end
end
Functions that return output arguments have variables for the outputs in their workspace.
However, parent functions only have variables for the output of nested functions if they
explicitly request them. For example, this function parentfun does not have variable y in
its workspace:
function parentfun
x = 5;
nestfun;
function y = nestfun
y = x + 1;
end
end
x = 5;
z = nestfun;
function y = nestfun
y = x + 1;
end
end
Input arguments
When you create a function handle for a nested function, that handle stores not only the
name of the function, but also the values of externally scoped variables.
For example, create a function in a file named makeParabola.m. This function accepts
several polynomial coefficients, and returns a handle to a nested function that calculates
the value of that polynomial.
function p = makeParabola(a,b,c)
p = @parabola;
function y = parabola(x)
y = a*x.^2 + b*x + c;
end
end
The makeParabola function returns a handle to the parabola function that includes
values for coefficients a, b, and c.
At the command line, call the makeParabola function with coefficient values of 1.3, .2,
and 30. Use the returned function handle p to evaluate the polynomial at a particular
point:
p = makeParabola(1.3,.2,30);
X = 25;
Y = p(X)
Y =
847.5000
Many MATLAB functions accept function handle inputs to evaluate functions over a
range of values. For example, plot the parabolic equation from -25 to +25:
fplot(p,[-25,25])
You can create multiple handles to the parabola function that each use different
polynomial coefficients:
firstp = makeParabola(0.8,1.6,32);
secondp = makeParabola(3,4,50);
range = [-25,25];
figure
hold on
fplot(firstp,range)
fplot(secondp,range,'r:')
hold off
From the level immediately above it. (In the following code, function A can call B
or D, but not C or E.)
From a function nested at the same level within the same parent function.
(Function B can call D, and D can call B.)
From a function at any lower level. (Function C can call B or D, but not E.)
function A(x, y)
B(x,y);
D(y);
function B(x,y)
C(x);
D(y);
function C(x)
D(x);
end
% Main function
% Nested in A
% Nested in B
end
function D(x)
E(x);
function E(x)
disp(x)
end
% Nested in A
% Nested in D
end
end
The easiest way to extend the scope of a nested function is to create a function handle and
return it as an output argument, as shown in Using Handles to Store Function Parameters.
Only functions that can call a nested function can create a handle to it.
Note: If you create a variable with the same name as a function, MATLAB cannot run that
function until you clear the variable from memory.
% double
testval = int8(10);
which max(testval)
built-in (matlabroot\toolbox\matlab\datafun\@int8\max)
% int8 method
R2012b
MATLAB
Language Fundamentals
Entering Commands
Search R2012
Search
Variable Names
On this page
Valid Names
Conflicts with Function Names
Valid Names
A valid variable name starts with a letter, followed by letters, digits, or underscores.
MATLAB is case sensitive, so A and a are not the same variable. The maximum length of
a variable name is the value that the namelengthmax command returns.
You cannot define variables with the same names as MATLAB keywords, such as if or
end. For a complete list, run the iskeyword command.
Examples of valid names:
Invalid names:
x6
6x
lastValue
end
n_factorial
n!
If you inadvertently create a variable with a name conflict, remove the variable from
memory with the clear function.
Another potential source of name conflicts occurs when you define a function that calls
load or eval (or similar functions) to add variables to the workspace. In some cases,
load or eval add variables that have the same names as functions. Unless these variables
are in the function workspace before the call to load or eval, the MATLAB parser
interprets the variable names as function names. For more information, see:
Search R2012
R2012b
MATLAB
Functions
Function Basics
Types of Functions
On this page
Search
You can call the main function from the command line or another program file, although
the local functions are only available to myfunction:
myfunction(pi)
ans =
16.1528
Nested functions are completely contained within another function. The primary
difference between nested functions and local functions is that nested functions can use
variables defined in parent functions without explicitly passing those variables as
arguments.
Nested functions are useful when subroutines share data, such as GUI applications that
pass data between components. For example, create a function that allows you to set a
value between 0 and 1 using either a slider or an editable text box. If you use nested
functions for the callbacks, the slider and text box can share the value and each other's
handles without explicitly passing them:
function myslider
value = 0;
f = figure;
s = uicontrol(f,'Style','slider','Callback',@slider);
e = uicontrol(f,'Style','edit','Callback',@edittext,...
'Position',[100,20,100,20]);
function slider(obj,~)
value = get(obj,'Value');
set(e,'String',num2str(value));
end
function edittext(obj,~)
value = str2double(get(obj,'String'));
set(s,'Value',value);
end
end
Local Functions
Nested Functions
This function has a single input, x. The @ operator creates the function handle.
You can use the function handle to evaluate the function for particular values, such as
y = s(pi)
y =
0.3130
Or, you can pass the function handle to a function that evaluates over a range of values,
such as fplot:
range = [0.01,0.1];
fplot(s,range)
http://www.mathworks.in/help/matlab/