SlideShare a Scribd company logo
1 of 163
Download to read offline
2.2. GLOBAL VARIABLE 151
https://sites.google.com/view/arunumrao
✞
x =
{
a = 1
a1 = 2
a2 = 3
}
✌
✆
Since variable names may only contain letters, digits and underscores, genvar-
name replaces any sequence of disallowed characters with an underscore. Also,
variables may not begin with a digit; in this case an underscore is added before
the variable name. Variable names beginning and ending with two underscores
(“ ”) are valid but they are used internally by Octave and should generally be
avoided, therefore genvarname will not generate such names. genvarname will
also make sure that returned names do not clash with keywords such as “for”
and “if”. A number will be appended if necessary. Note, however, that this
does not include function names, such as “sin”. Such names should be included
in avoid if necessary.
2.2 Global Variable
A variable that has been declared as global may be accessed from within a
function body without having to pass it as a formal parameter. A variable is
set global by using global statement. Three variables ‘x’, ‘y’ and ‘z’ with ‘y’=1
are set as global variable in following example.
✞
>>> global x y=1 z;
✌
✆
Global variable can be assigned only once. If same variable is required to use
as global variable again, first use
✞
1 >>> clear <global variable >
✌
✆
or
✞
1 >>> clear all
✌
✆
A variable set global outside a function can not be assigned a value from the
body of the function. But it just copy the value to global variable for use inside
the function.
✞
1 >>> global x; # global variable x
>>> function f(x)
3 >>> x=1; # assigned value 1 withing function body
>>> x # call variable within function body , prints 1
5 >>> endfunction
>>> f() # call function
7 >>> x # call global variable , prints [](0 x0) for null value
✌
✆
152 Variable
✞
x = 1
x = [](0 x0)
✌
✆
2.2.1 Is Variable Global
isglobal is used to find whether a variable is global or not. It returns ‘true’ if
variable is global otherwise ‘false’.
✞
>>> global x; # global variable x
2 >>> isglobal ("x")
✌
✆
✞
ans = 1
✌
✆
2.3 Persistant Of a Variable
A variable that has been declared persistent within a function will retain its con-
tents in memory between subsequent calls to the same function. The difference
between persistent variables and global variables is that persistent variables are
local in scope to a particular function and are not visible elsewhere.
✞
1 >>> global x=1; # global scope; can be called or copy
anywhere
>>> isglobal ("x")
3 >>> function f(y);
>>> y=2; #local scope; within the function body
5 >>> endfunction
✌
✆
✞
ans = 1
✌
✆
2.3.1 Clear Symbol From Table (clear)
Delete the names matching the given patterns from the symbol table. The
pattern may contain the following special characters:
1. ‘?’ : Match any single character.
2. ‘*’ : Match zero or more characters.
3. ‘[ ¡list¿ ]’ : Match the list of characters specified by list.
If the first character is ‘!’ or ‘ˆ’ then matching of all characters is performed
excepting those specified by a list. For example, the pattern [a-zA-Z]’ will match
all lower and upper case alphabetic characters. For example
2.3. PERSISTANT OF A VARIABLE 153
https://sites.google.com/view/arunumrao
✞
1 >>> clear foo b*r
✌
✆
clears the name ‘foo’ and all names that begin with the letter ‘b’ and end with
the letter ‘r’. If clear is called without any arguments, all user-defined variables
(local and global) are cleared from the symbol table.
2.3.2 Show Files in Directory (what)
what command is used to find all the Octave files in the directory. Syntax is
✞
1 >>> what (<dir name >)
✌
✆
If ‘dir name’ is empty, it returns the list of Octave files from the current path.
2.3.3 Function Name Type (which)
It displays the type of each name. If name is defined from a function file, the
full name of the file is also displayed.
2.3.4 Scope of Variable (who)
who returns the scope of variable supplied by pattern. For example
✞
1 >>> global x;
>>> what ("x")
✌
✆
✞
Variables in the current scope:
x
✌
✆
Or
✞
>>> global x;
2 >>> who("global")
✌
✆
✞
Global variables :
x
✌
✆
2.3.5 Exit From Loop (exist)
exist returns whether the variable, function, file or director specifiend as argu-
ment to the function are exist or not exist in the sytem. The syntax of this
function is
✞
>>> exist(<name >, <type >)
✌
✆
154 Functions
There are four types of ‘type’ values.
Type Description
“var” Check only for variables
“builtin” Check only for built-in functions
“file” Check only for files
“dir” Check only for directories
Example is
✞
1 >>> exist("meaning","var")
✌
✆
✞
ans = 0
✌
✆
3.1. FUNCTION 155
https://sites.google.com/view/arunumrao
3Functions
Octave is written in ‘C’ and ‘C++’. Unlike ‘C++’ Octave does not required
pre-definition of variable. Variables are automatically converted into integer,
character etc forms according to the values passed to them. In other words, a
value is assigned to a variable by juggling. If a variable ‘a’ is being added with
‘2’ then the variable ‘a’ would be considered as an integer type variable. But if
it is to be added with ‘2.00202201220215’ then variable ‘a’ will be considered as
an long type variable. In summary type of a variable is considered as it is being
used. Each statement performed internally should be terminated by ‘;’. The
statement whose result would be display in output window should not end with
‘;’. Statements, strings and variables are grouped inside a parenthesis brackets,
ie ‘(’ ... ‘)’. Generally octave uses following code conventions. According to the
Code Conventions for the Octave Programming Language it is recommended:
1. Start each statement on a new line.
2. Write no more than one simple statement per line.
3. Break compound statements over multiple lines.
Following example uses two integers 2, 3 & ‘;’ and prints their result at output
window.
✞
1 /* Without pre -identification of *
*variable and terminated by ’;’*/
3 >>> a=2;
/* Without pre -identification of *
5 *variable and terminated by ’;’*/
>>> b=3;
7 /* sum of two variables is called *
*line does not terminated by ’;’*/
9 >>> a+b
✌
✆
✞
ans = 5
✌
✆
If result of an operation is not assigned to a variable, then result is automatically
assigned to ‘ans’ variable.
3.1 Function
Function, in computer science is a set of instructions. This set of instruction is
collectively called a script or code. Codes inside the function are not executed
until unless function is not called. Some times more than one functions or com-
mands are successively used for a specific purpose. The re-usability of these sets
156 Functions
of functions or commands is very problematic. Hence these set of functions or
commands are put inside a new function defined by user. Now this new defined
function can be used as and when required. Octave is a strong language. It
supports grouping of expressions. A group block started with reserved keyword
and ended with the same keyword prefixed with ‘end’.
✞
1 function f(x)
<expression or codes >
3 endfunction
✌
✆
✞
1 for <condition >
<expression or codes >
3 endfor
✌
✆
Octave has strong commenting support. Commenting are those lines which
are inserted inside the program code to make it better understandable. Single
line commenting is made with ‘#’ or ‘%’ symbols at the beginning of a line.
These comments are just skipped by compilers and are not executed as part
of the program. Entire block of lines can be commented by enclosing the lines
between matching ‘#{ and ‘#} or ‘%{ and ‘%} markers.
✞
1 #Beginning of a function
function f(x)
3 <expression or codes >
#{
5 This block shall be executed
when function f(x) is called.
7 #}
endfunction
✌
✆
3.1.1 Defining A Functions
In its simplest form, the definition of a function named name looks like this:
✞
>>> function <name >
2 >>> <body >
>>> endfunction
✌
✆
A function name should be a valid name. A valid function name contains letters,
digits and underscores. A function name should not starting with a digit. In
octave, the parameters are passed to a function as shown in following synopsis.
✞
1 >>> function <name > (<arg -list >)
>>> <body >
3 >>> endfunction
✌
✆
3.1. FUNCTION 157
https://sites.google.com/view/arunumrao
A function either modified to a predefined variable by changing its value or it
returns a value as result. A function with single return value is defined as shown
below.
✞
1 >>> function <out var > = <name > (<arg -list >)
>>> <body >
3 >>> endfunction
✌
✆
A working example is given below:
✞
1 >>> function o = myAvg (a, b)
>>> o = (a+b)/2;
3 >>> endfunction
✌
✆
If you want to define a function with output variables then be careful in writing
the statement line in which output variable is being assigned the result. For
example, in above example when we call the function with appropriate numbers
of parameters, we see that the output is shown with default output variable, i.e.
ans.
✞
1 >>> myAvg (4, 5)
✌
✆
✞
ans = 4.5000
✌
✆
Output is not shown with out variable ‘o’ as we expected here. This is due
to the termination of statement line with symbol ‘;’. Therefore, to assign the
result to output variable, do not terminate the corresponding statement line by
the line terminating symbol ‘;’ as shown in the following example.
✞
1 >>> function o = myAvg (a, b)
>>> o = (a+b)/2
3 >>> endfunction
✌
✆
Now, call the function with appropriate numbers of parameters either by ter-
minating it or by non terminating it.
✞
1 >>> myAvg(4,5);
✌
✆
✞
o = 4.5000
✌
✆
✞
1 >>> myAvg(4,5)
✌
✆
✞
o = 4.5000
ans = 4.5000
✌
✆
158 Functions
Now, here are two forms of outputs. If called a function with terminating
symbol, then only user defined out variable is shown in the screen. Similarly,
when called function is not terminated, then both user defined output variable
and default output variable are shown in the screen. Her, the function can be
called in its standard form too:
✞
>>> [a]= myAvg (4,5);
✌
✆
✞
o = 4.5000
✌
✆
✞
1 >>> [a]= myAvg (4,5)
✌
✆
✞
o = 4.5000
a = 4.5000
✌
✆
Arguments and their corresponding values may also be assigned in ‘argument
list’ region.
✞
>>> function myFunc(msg="Hello!!!")
2 >>> printf(msg);
>>> endfunction
4 >>> myFunc ()
✌
✆
✞
Hello !!!
✌
✆
The multiple output variables can be used in a function if output variables are
arranged in a vector form. Each element has unique output value and they are
independent of each other.
✞
1 >>> function [<ret vector >] = <func name >(<args list >)
>>> <contents of function i.e. body >
3 >>> endfunction
✌
✆
Example is
✞
1 >>> x=0;
>>> function [y, z]= myFunc(x)
3 >>> y = x/10;
>>> z = x*2;
5 >>> endfunction
>>> [y,z]= myFunc (10)
✌
✆
✞
y = 1
z = 20
✌
✆
3.1. FUNCTION 159
https://sites.google.com/view/arunumrao
If output variables are more than the return values in the function statements
then output variables without return value in the statement of the body are
assigned as null value.
✞
>>> x=0;
2 >>> function [y, z, t]= myFunc(x)
>>> y = x/10;
4 >>> z = x*2;
>>> # t is not assigned any return value
6 >>> endfunction
>>> [y,z,t]= myFunc (10)
✌
✆
✞
y = 1
z = 20
t = [](0 x0)
✌
✆
3.1.2 Arguments
Arguments are those values which are passed to a function. These arguments
are used by the function itself for its internal operations.
✞
1 >>> Func (<argument 1>, <argument 2>, ..., <argument n>)
✌
✆
3.1.3 Key Words
Some function names are used by Software itself. These function names can not
be redefined or reused by the program. Followings are the key words used by
Octave itself.
case catch classdef continue
do else elseif end
end try catch end unwind protect endclassdef endenumeration
endevents endfor endfunction endif
endmethods endparfor endproperties endswitch
endwhile enumeration events for
function global if methods
otherwise parfor persistent properties
return static switch try
until unwind protect unwind protect cleanup while
160 Functions
3.1.4 Macro
Macro is a group of two or more functions interdependent with each other to
obtain a common goal.
3.1.5 Variables
Variables are group of alphanumeric valid characters. Variables store numeric
and non-numeric data that can be obtained by just calling the variable names.
Each variable has its own scope that depends on the method of its definition. In
Octave ‘type’ of variable is automatically assigned when it is assigned a value.
3.1.6 Number Format
Octave uses double precision floating points as default number format upto five
significant figures. This format can be changed by using function format with
suitable options. Options are ‘short’, ‘long’, ’rat’, ‘hex’, ‘native-bit’ or ‘bank’. If
format is invoked without any options, default format is restored. The options
used have following meanings.
Option Meaning
short Prints five significant figures.
long Prints fifteen significant figures.
rat Prints rational form of numbers.
hex Prints hexadecimal form of numbers.
native-bit Prints binary form of numbers.
bank Prints only two digits after decimal.
✞
1 >>> format <type >
✌
✆
For example
✞
1 >>> format short;
>>> pi
✌
✆
✞
ans =
3.1416
✌
✆
3.1. FUNCTION 161
https://sites.google.com/view/arunumrao
✞
>>> format long ;
2 >>> pi
✌
✆
✞
ans =
3.14159265358979
✌
✆
✞
>>> format hex;
2 >>> pi
✌
✆
✞
ans =
400921fb 54442d18
✌
✆
3.1.7 Number of Input Arguments (nargin)
Octave has a table list called nargin that stores the variables of any size. Each
time a function is called, nargin is automatically initialized to the number of
arguments that have actually been passed to the function.
✞
>>> x=0;
2 >>> function [y, z] = myFunc(x)
>>> y = x/10;
4 >>> z = nargin;
>>> endfunction
6 >>> [y, z] = myFunc (10)
✌
✆
✞
y = 1
z = 1
✌
✆
nargin also tells about the number of arguments a function can accept.
✞
>>> x=0;
2 >>> function y=myFunc(x)
>>> y = x/2;
4 >>> endfunction
>>> function z=myFuncA(x,y)
6 >>> z = (x+y)/2;
>>> endfunction
8 >>> nargin("myFunc")
>>> nargin("myFuncA ")
✌
✆
✞
ans = 1
ans = 2
✌
✆
162 Functions
3.1.8 Number of Output Arguments (nargout)
nargout tells about the number of return arguments present in the function
definition.
✞
>>> x=0;
2 >>> function y = myFunc(x)
>>> y = x/2;
4 >>> endfunction
>>> function [z, t] = myFuncA(x, y)
6 >>> z = (x+y)/2;
>>> endfunction
8 >>> nargout ("myFunc")
>>> nargout ("myFuncA")
✌
✆
✞
ans = 1
ans = 2
✌
✆
3.1.9 How to Use a Function (usage)
If a function is not called properly, then this function tells about the proper use
of the function. See in the following example:
✞
>>> x=0;
2 >>> function [y, z]= myFunc(x)
>>> if (nargin != 1)
4 >>> usage ("myFunc (<vector >)");
>>> else
6 >>> y=x/10;
>>> z = nargin;
8 >>> endif
>>> endfunction
10 >>> [y,z]= myFunc()
✌
✆
✞
usage: myFunc (<vector >)
✌
✆
3.1.10 Error (error)
This function is used to show the error occurs if any.
✞
1 >>> x=0;
>>> function y=myFunc(x)
3 >>> if (! isvector (x))
>>> y = x/2;
3.1. FUNCTION 163
https://sites.google.com/view/arunumrao
5 >>> else
>>> error("x should not be a vector.");
7 >>> endif
>>> endfunction
9 >>> myFunc ([10 ,20 ,30])
✌
✆
✞
error: x should not be a vector.
✌
✆
3.1.11 Error Number (errno)
It returns the current value of the system-dependent variable errno.
✞
1 >>> err = errno ()
✌
✆
‘err’ will be zero if there is no error otherwise error number if there is an error.
3.1.12 List of Error Numbers (errno list)
errno list returns the list of errors and their corresponding numbers.
✞
1 >>> errno_list
✌
✆
✞
ans =
{
E2BIG = 7
EACCES = 13
EAGAIN = 11
......
EXDEV = 18
}
✌
✆
3.1.13 Last Error (lasterr)
lasterr returns the error encountered to Octave most recently during the current
session.
✞
>>> lasterr;
✌
✆
3.1.14 Last Warning (lastwarn)
lastwarn returns the recent most warning shown by the Octave during the ses-
sion. If there is not any warning during the session, it return empty result.
✞
1 >>> lastwarn ;
✌
✆
164 Functions
3.1.15 Variable Input Arguments (varargin)
varargin appears as one argument of a function and it stores the number of
arguments that can be accept by a function. varargin list is initialized auto-
matically when a function is initialized. In other words, if user wants to supply
variable numbers of arguments to a function then argument varargin should be
used as a function argument. The syntax is
✞
1 >>> function [<return value vector >] = <function name by
user >( varargin )
>>> disp (varargin {i}) #ith element of variable argument
3 >>> endfunction
✌
✆
Example is
✞
1 >>> function myVarFunc (varargin )
>>> for i=1: length(varargin )
3 >>> disp (varargin {i});
>>> disp ("n");
5 >>> endfor
>>> endfunction
7 >>> myVarFunc (10, 20, 30)
>>> myVarFunc (10, 20, 30, 40)
✌
✆
✞
ans =
10
20
30
ans =
10
20
30
40
✌
✆
3.1.16 Variable Output Arguments (varargout)
varargout returns variable outputs. varargout list is initialized automatically
when a function is initialized. The syntax is
✞
1 >>> function varargout = <function name by user >( varargin )
>>> varargout {i}=i #ith element as ith out argument
3 >>> endfunction
✌
✆
Example is
3.1. FUNCTION 165
https://sites.google.com/view/arunumrao
✞
1 >>> function varargout = myVarFunc (varargin )
>>> for i=1: length(varargin )
3 >>> varargout {i}= varargin {i};
>>> endfor
5 >>> endfunction
>>> [a, b, c, d] = myVarFunc (10, 20, 30)
✌
✆
✞
ans =
10
20
30
error: element number 4 undefined in return list
✌
✆
3.1.17 Tilde ( )
is used in place of input argument name of a function to ignore the corre-
sponding argument value and not stored it to any variable. Syntax is
✞
1 >>> function [<ret vector >] = <func name >(~, <other arg(s) >)
>>> val = <any other argument >
3 >>> endfunction
✌
✆
The working example is
✞
1 >>> x=0;
>>> function myFunc(~, x)
3 >>> y = x+2;
>>> endfunction
5 >>> myFunc(10, 20)
✌
✆
✞
ans = 22
✌
✆
The value of nargin is not affected by using this declaration.
3.1.18 Whether Argument is Out Type (isargout)
isargout returns ‘true’ if string is a valid out argument otherwise returns ‘false’.
✞
1 >>> x=0;
>>> function y = myFunc(~, x)
3 >>> isargout (1) # true as y is out argument
>>> isargout (2) # false as there is no
5 >>> # second out argument
>>> y=x+2;
7 >>> endfunction
>>> myFunc(10, 20)
✌
✆
166 Functions
✞
ans = 1 % only one out argument ‘y’
ans = 0 % No second argument
ans = 22
✌
✆
3.1.19 Return Command (return)
When Octave encounters the keyword return inside a function or script, it re-
turns control to the caller immediately. At the top level, the return statement is
ignored. A return statement is assumed at the end of every function definition.
✞
1 >>> x=0, y=0;
>>> function z= myFunc(x,y)
3 >>> for i=1:x
>>> if(i==y)
5 >>> z=i;
>>> return;
7 >>> endif
>>> endfor
9 >>> endfunction
>>> myFunc (30, 15)
✌
✆
✞
ans = 15
✌
✆
3.1.20 Add Environmental Path (addpath)
It add named directories to the function’s search path. Search paths are those
directories where a function looks-up for the files.
✞
1 >>> addpath (<directory path >)
✌
✆
Example is
✞
1 >>> path = addpath("/")
✌
✆
It returns all Octave’s search paths.
3.1.21 Remove Environmental Path (rmpath)
It removes named directories from the function’s search path.
✞
1 >>> rmpath(<directory path >)
✌
✆
3.1. FUNCTION 167
https://sites.google.com/view/arunumrao
3.1.22 Lock A Function (mlock)
Locks the current function into memory so that it can’t be clear. mlock must
be called from the body of the function. Right order of syntax is
✞
1 >>> function myFuncA ()
>>> mlock() # always called from the function body
3 >>> endfunction
>>> myFuncA ()
✌
✆
3.1.23 Unlock A Function (munlock)
To unlock a locked function, munlock is used. Its argument is a function name
that is previously locked. munlock can be called from inside or outside of the
function body. From inside the body
✞
>>> function myFuncA ()
2 >>> mlock()
>>> munlock () # call from the body of function
4 >>> endfunction
>>> myFuncA ()
6 >>> mislocked ("myFuncA")
✌
✆
✞
ans = 0
✌
✆
From outside the function body, this function needs input argument which is
name of the function being unlocked.
✞
1 >>> function myFuncA ()
>>> mlock()
3 >>> endfunction
>>> myFuncA ()
5 >>> munlock(" myFuncA") # call from outside of
>>> # the body of function
7 >>> mislocked ("myFuncA")
✌
✆
✞
ans = 0
✌
✆
3.1.24 Whether A Function is Locked (mislocked)
It returns ‘true’ if the current function or the function supplied as argument
is locked otherwise returns ‘false’. mislocked may be called from the body of
function or outside the function.
168 Functions
✞
1 >>> function myFuncA ()
>>> mlock()
3 >>> mislocked () # call from the body of function
>>> endfunction
5 >>> myFuncA ()
✌
✆
✞
ans = 1
✌
✆
From outside the function body, this function must be supplied name of function
that is being checked whether it is locked or not.
✞
1 >>> function myFuncA ()
>>> mlock()
3 >>> endfunction
>>> myFuncA ()
5 >>> mislocked ("myFuncA ")
✌
✆
✞
ans = 1
✌
✆
3.2 Function Handler
A function handle point to another inbuilt or user define function. The function
object is accesses by prefixing ‘@’ symbol. Without ‘@’ symbol, the value is
treated as string. The syntax is
✞
1 >>> h = @<function name >
✌
✆
Example is
✞
1 >>> f = @sin ;
>>> f(pi /3)
✌
✆
✞
ans = 0.86603
✌
✆
3.2.1 Whether Argument is Function Handle (is function handle)
It return ‘true’ if argument is a function handle.
✞
1 >>> f = @sin ;
>>> is_function_handle (f)
✌
✆
✞
ans = 1
✌
✆
3.2. FUNCTION HANDLER 169
https://sites.google.com/view/arunumrao
3.2.2 Anonymous Functions
An anonymous function has no name, but it is identified by its handle which
assigned the anonymous function’s object address. An anonymous function can
be defined by using syntax like
✞
1 >>> f = @(<argument list >) <expression >
✌
✆
Example is
✞
1 >>> f = @(x) x.^2;
>>> f(2)
✌
✆
✞
ans = 4
✌
✆
3.2.3 Sub Functions
A function has a complete body and it may call another functions. When a
function is called inside the body of main function then called function is known
as sub function of the main function.
✞
1 >>> function myFuncA ()
>>> printf ("in myFuncA , calling myFuncB n");
3 >>> myFuncB ();
>>> endfunction
5 >>> function myFuncB ()
>>> printf ("in myFuncB , calling myFuncC n");
7 >>> myFuncC ();
>>> endfunction
9 >>> function myFuncC ()
>>> printf ("in myFuncC n");
11 >>> endfunction
✌
✆
For the function ‘myFuncA’, function ‘myFuncB’ is a sub function while for ‘my-
FuncB’ function ‘myFuncC’ is sub function. Sub functions are used to carryout
short computations for the main function.
3.2.4 Nested Function
A function within another function is called nested functions. In the following
example, ‘myFuncA’ is nested function for the outer function ‘myFunc’.
✞
1 >>> function y=myFunc()
>>> x=10;
3 >>> myFuncA ();
>>> y=x;
170 Conditional Function
5 >>> function myFuncA ()
>>> x=20;
7 >>> endfunction
>>> endfunction
9 >>> myFunc ()
✌
✆
✞
ans = 20
✌
✆
4.1. LOOP CONDITION 171
https://sites.google.com/view/arunumrao
4Conditional Function
Conditional operators are those functions which allow to execute specific region
if certain conditions are met. There are two categories of conditional functions.
Loop conditions and switch conditions.
4.1 Loop Condition
Loop condition provides to execute same region again and again until specific
condition is not met to exit the loop. Followings are the loop conditions.
4.1.1 For Condition (for)
for statement is used to iterate the code body like the syntax
✞
1 >>> for variable =initial:incr :limit
>>> .... code statement ....
3 >>> endfor
✌
✆
for statement is useful when initialized variable is to be used in statement.
Variable is started with ‘initial’ value. After each iteration, variable is increased
by increment ‘incr’. When variable superseded its ‘limit’, for statement seizes
to execute codes.
✞
1 >>> for i=0:2:10
>>> i
3 >>> endfor
✌
✆
✞
i = 0
i = 2
i = 4
i = 6
i = 8
i = 10
✌
✆
It will remember that each for statement must be closed by endfor. for state-
ment can also be used like
✞
for variable = initial:limit
2 .... code body ....
endfor
✌
✆
In this type of expression of for statement, variable is increased by ‘one’ after
each iteration.
172 Conditional Function
✞
1 >>> for i=1:5
>>> i
3 >>> endfor
✌
✆
✞
i = 1
i = 2
i = 3
i = 4
i = 5
✌
✆
for statement also accepts the array elements for performing loop.
✞
1 >>> for i={1,2, "A"}
>>> i
3 >>> endfor
✌
✆
✞
i =
{
[1,1] = 1
}
i =
{
[1,1] = 2
}
i =
{
[1,1] = A
}
✌
✆
Here each [1,1] represents the rows and columns of each array element. A two
dimensional array may also be used.
✞
>>> for i={1 ,2;"A","B"}
2 >>> i
>>> endfor
✌
✆
✞
i =
{
[1,1] = 1
[2,1] = A
}
i =
{
[1,1] = 2
[2,1] = B
}
✌
✆
4.1. LOOP CONDITION 173
https://sites.google.com/view/arunumrao
for statement and matrix expression may be correlated with each other. The
method is given in following example.
✞
>>> for i=[1 ,2;3 ,4]
2 >>> i
>>> endfor
✌
✆
✞
i =
1
3
i =
2
4
✌
✆
In above procedure, columns are executed in one iteration. An key-value relation
of for statement is
✞
>>> x.a=1; # Set key ’a’ for value ’1’
2 >>> x.b=2; # Set key ’b’ for value ’2’
>>> ## Call value and key from variable ’x’ in matrix form
4 >>> for [val , key]=x;
>>> key # Print key
6 >>> val # Print value
>>> endfor # End for loop
✌
✆
✞
key = a
val = 1
key = b
val = 2
✌
✆
4.1.2 While Condition (while)
while statement performs looping until the condition is met.
✞
>>> i=1;
2 >>> while(i<10)
>>> i
4 >>> i++;
>>> endwhile
✌
✆
✞
i = 3
i = 4
i = 5
i = 6
i = 7
174 Conditional Function
i = 8
i = 9
✌
✆
Each while statement must be closed with endwhile.
4.1.3 Do-until Condition (do ... until)
The do-until statement is similar to the while statement, except that it re-
peatedly executes a statement until a condition becomes true. The test of the
condition is at the end of the loop, so the body of the loop is always executed
at least once.
✞
1 >>> i=1;
>>> do
3 >>> i
>>> i++;
5 >>> until(i==10)
✌
✆
✞
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
✌
✆
4.2 Switch Condition (switch)
Switch conditions has two results, (i) if the condition is ‘true’ and (ii) if the
condition is ‘false’. Hence the code bodies are executed if condition is either
‘true’ or ‘false’.
4.2.1 If Condition (if)
if condition is used to execute enclosed codes if certain conditions are met as
desired by the user.
✞
1 >>> i=1;
>>> if(i<2) # If this statement is true
3 >>> disp ("Variable ’i’ is less than two");
>>> endif
✌
✆
✞
Variable ’i’ is less than two
✌
✆
4.2. SWITCH CONDITION (SWITCH) 175
https://sites.google.com/view/arunumrao
Each if statement opened must be closed with endif. else statement can also
be used for false condition, if there may be.
✞
1 >>> i=3;
>>> if(i<2) # If this statement is true
3 >>> disp ("Variable ’i’ is less than two");
>>> else
5 >>> disp ("Variable ’i’ is greater than two");
>>> endif
✌
✆
✞
Variable ’i’ is greater than two
✌
✆
4.2.2 Break Command (break)
break command stops the current process of loop and allow exit from the loop.
break command is always used inside a loop. Example is
✞
1 >>> for(i=1:1:10)
>>> if(i>5)
3 >>> disp ("Looped by five times")
>>> break;
5 >>> endif
>>> disp (i)
7 >>> endfor
✌
✆
✞
1
2
3
4
5
Looped by five times
✌
✆
4.2.3 Continue Command (continue)
The continue command, like break, can be used only inside the while, do-until,
or for loops. It skips over the rest of the loop body, causing the next cycle
around the loop to begin immediately. Contrast this with break, which jumps
out of the loop altogether. The syntax is
✞
>>> for x = <value >
2 >>> if (<condition >)
>>> continue ;
4 >>> endif
>>> printf (<print statements >);
6 >>> endfor
✌
✆
176 Conditional Function
Example is
✞
>>> for x = 1:5
2 >>> if (x==3)
>>> continue ;
4 >>> endif
>>> printf ("%dn",x);
6 >>> endfor
✌
✆
✞
1
2
% x=3 is skipped due to continue command
4
5
✌
✆
4.2.4 Try-Catch Statement
try ... catch statement is used within loop environment. The syntax of this
function is
✞
1 >>> try
>>> <try statement >
3 >>> catch
>>> <catch statement >
5 >>> end_try_catch
✌
✆
Each try ... catch must be closed by using end try catch keyword. Example is
✞
1 >>> x=1;
>>> for(x =1:10)
3 >>> try
>>> if(x<5)
5 >>> x
>>> endif
7 >>> catch
>>> x
9 >>> end_try_catch
>>> endfor
✌
✆
try keyword tries to execute the subsequent codes which are within its scope. If
codes are successfully executed then it returns nothing. If there is error during
the execution of codes, it throws an error which is captured through the catch.
try ... catch statement has advantage that it does not exit the program. It
either shows default errors if it occurs during the code execution or simply skips
the current loop iteration. See following two examples:
4.2. SWITCH CONDITION (SWITCH) 177
https://sites.google.com/view/arunumrao
✞
>>> x=1;
2 >>> for(x=1:10)
>>> fread("a","r")
4 >>> endfor
✌
✆
✞
error: fread: invalid stream number = -1
✌
✆
Above example shows an error of invalid stream number as the file being opened
is not present in the default temporary directory of Octave. Again the modified
example is
✞
1 >>> x=1;
>>> for(x=1:10)
3 >>> try
>>> fread("a","r")
5 >>> catch
>>> end_try_catch
7 >>> endfor
✌
✆
It does not shows any error or warning.
178 File Operation
5.1. PC INFO (INFO) 179
https://sites.google.com/view/arunumrao
5File Operation
5.1 PC Info (info)
Octave provides expanded environment and application of C like languages. It
means, with Octave, we not only do computations but we can also access the
files/memory of the host system. The file operation capability of Octave is
similar to the C programming languages. In the following sections, we shall
discuss about the read/write/update the files/directories of host system.
5.1.1 System Architecture (computer)
It returns the information regarding the architecture of the computer system
under which it was compiled.
✞
1 >>> computer ()
✌
✆
✞
i686-w64- mingw32
✌
✆
5.1.2 Is Windows (ispc)
It returns true if Octave is running on windows operating system.
✞
1 >>> ispc ()
✌
✆
✞
ans = 1
✌
✆
5.1.3 Is Linux (isunix)
It returns true if Octave is running on unix operating system otherwise it returns
false.
✞
1 >>> isunix()
✌
✆
✞
ans = 0
✌
✆
180 File Operation
5.1.4 Parent Machine (isdeployed)
isdeployed checks whether Octave is running in same machine in which it is
compile or not. If it is running in other machine, it returns ‘true’ value otherwise
‘false’ value.
✞
1 >>> isdeployed ()
✌
✆
✞
ans = 0
✌
✆
5.1.5 Version (version)
It returns the version of the Octave.
✞
1 >>> v = version ()
✌
✆
5.1.6 License (license)
It returns the license of the Octave.
✞
1 >>> v = license ()
✌
✆
✞
v = GNU General Public License
✌
✆
5.2 Directory Management
In this section we will discuss about the creation of directory, files, their access-
ing, reading, renaming, deletion etc.
5.2.1 Make a Dir (mkdir)
mkdir creates a directory in the current path used by Octave. If directory is
present then it just returns true value. If a directory is successfully created, it
returns true value otherwise false value. Syntax is
✞
1 >>> [STATUS , MSG , MSGID] = mkdir (PARENT , DIR)
✌
✆
Example of creating a directory “a” is
✞
1 >>> mkdir("a");
✌
✆
The output is
5.2. DIRECTORY MANAGEMENT 181
https://sites.google.com/view/arunumrao
✞
ans = 1
✌
✆
5.2.2 List Directory (ls)
It returns the list of all directories present in the current working directory.
5.2.3 Change Directory (cd)
It changes the current directory to the new location as specified by the directory
path of this command. Path may be either relative or absolute. The syntax of
this function is
✞
1 >>> cd <dir name >
>>> cd(<dir name as string >)
✌
✆
Another method to change the directory is chdir.
✞
>>> chdir(<dir path >)
✌
✆
5.2.4 Directory (dir)
dir returns the all files and sub directories present in the current directory.
✞
1 >>> dir()
✌
✆
5.2.5 Is Directory (isdir)
isdir returns ‘true’ if relative path or absolute path is a directory otherwise
returns ‘false’.
✞
1 >>> isdir(<relative or absolute file path >)
✌
✆
5.2.6 Remove Directory (rmdir)
rmdir removes the directory whose name is supplied as argument to this func-
tion. It also removes sub directories and files inside the target directory.
✞
1 >>> rmdir(<relative or absolute file path >)
✌
✆
182 File Operation
5.2.7 Read Directory (readdir)
readdir reads the directory whose name is supplied as argument to the function.
Syntax is given below
✞
1 >>> [files , error , msg] = readdir (< directory name >)
✌
✆
It returns three output handlers. First array is the list of all files inside the
directory. Second array is error type encounters while Octave tries to read
the directory and third is message returned by Octave when it read directory
successfully or not.
5.2.8 Temporary Directory (tempdir)
It returns the path of temporary directory used by the Octave for temporary
operation/execution. In this directory, temporary files are used for internal ap-
plication of Octave. When the session or application of Octave ended, temporary
files are removed from the directory. This function is used like
✞
1 >>> tempdir
✌
✆
Another method is
✞
1 >>> tempdir ()
✌
✆
✞
ans = C: DOCUME ~1 ADMINI ~1 LOCALS ~1 Temp 
✌
✆
5.2.9 Temporary Name (tempname)
It returns the name of temporary directory used by the Octave for temporary
operation/execution. User can set another directory as temporary directory as
and when required. Use this function
✞
1 >>> tempname
✌
✆
✞
1 >>> tempname ()
✌
✆
✞
ans = C: DOCUME ~1 ADMINI ~1 LOCALS ~1 Temp oct -2
✌
✆
5.2. DIRECTORY MANAGEMENT 183
https://sites.google.com/view/arunumrao
5.2.10 Attribute of File (fileattrib)
It returns the attributes of a file supplied as argument to the function. The
syntax of this function is
✞
1 >>> [status , result , msgid] = fileattrib (<file path >)
✌
✆
If Octave is successful in getting of attribute ‘status’ is ‘1’. ‘result’ returns arrays
of the result on successful retrieval of attributes. ‘msgid’ is id of message shown
by Octave if any.
5.2.11 File Marker (filemarker)
It is used to find or set the character used to separate file-name from the the
sub-function names contained within the file. The syntax is
✞
1 >>> val = filemarker () # for query
>>> filemarker (<new val >, " local") # for set the character
✌
✆
5.2.12 File Parts (fileparts)
fileparts returns the directory in which file is placed, name of file, extension of
file and version. Syntax is
✞
>>> [dir , name , ext , ver] = fileparts (<file name >)
✌
✆
5.2.13 File Separator (filesep)
filesep returns the separator of directory/file in path name. It may be forward
slash or backward slash. File separator depends on the Operating System used
by Octave.
✞
1 >>> filesep
✌
✆
✞
ans = 
✌
✆
5.2.14 Copy File (copyfile)
copyfile copies a file with another name. The path of directory may be relative
or absolute. Syntax is
✞
1 >>> [status , msg , msgid] =
>>> copyfile (<source file >, <dest file >)
✌
✆
184 File Operation
If the destination file exists, it overwrites the destination file by the file being
copied without any warning.
5.2.15 Move File (movefile)
movefile moves a file from one directory to another directory. The path of
directory may be relative or absolute. Syntax is
✞
>>> [status , msg , msgid] =
2 >>> movefile (<source file >, <dest file >)
✌
✆
‘status’ handle returns the status of the operation, ‘msg’ returns message and
‘msgid’ is the id of the last message shown by Octave.
5.2.16 Rename a File (rename)
rename renames a file name with another file name. Syntax is
✞
>>> [err , msg] = rename (<old name >, <new name >)
✌
✆
It shows error if there is any error arises during this process & message if any
returned by the Octave.
5.2.17 Delete a File (unlink)
unlink deletes a file. Syntax is
✞
1 >>> [err , msg] = unlink(<file name >)
✌
✆
It shows error if there is any error arises during this process & message if any
returned by the Octave.
5.3 I/O Operation
Reading, writing and managing of a file is known as file operation. Input and
output operations are reading and writing of a file. The functions which are
used in file reading and writing are explained below.
5.3.1 End of File (feof)
Returns ‘1’ if an end-of-file condition has been encountered for a given file
and ‘0’ otherwise. It will only return ‘1’ if the end of the file has already been
encountered otherwise next read operation will result in an end-of-file condition.
5.3. I/O OPERATION 185
https://sites.google.com/view/arunumrao
✞
1 >>> f = fopen ("myfile.txt", "r");
>>> while (! feof (f) )
3 >>> fgetl (f) # Read line by line
>>> endwhile
5 >>> fclose (f);
✌
✆
It will print file contents line by line of the file.
5.3.2 Clear a File Stream (fclear)
It clears the stream state for the specified file.
✞
1 >>> f = fopen ("myfile.txt", "r");
>>> fclear(f);
3 >>> fclose (f);
✌
✆
5.3.3 Open/Create a File (fopen)
fopen command is used to open a file either in read or in write or in append
mode. fopen command is used like
✞
1 >>> f = fopen ("newfile.txt", "w");
✌
✆
It creates a file in the current working directory of Octave. Each and every file
opened must be closed by using fclose command. It returns ‘-1’ if there is any
error in the opening of a file otherwise it returns stream id. If multiple files are
required to be opened, each opened file stream should be given a unique stream
id by using hte sytax like
✞
1 >>> f1 = fopen ("a.txt", "r");
>>> f2 = fopen ("b.txt", "r");
✌
✆
5.3.4 Close a File (fclose)
fclose closes the previously opened file. The file closing operation is performed
like
✞
>>> f = fopen ("newfile.txt", "w");
2 >>> fclose(f);
✌
✆
If there are multiple file streams opened by function fopen by using same stream
id then fclose closes only last open file until stream id is not provided as argu-
ment. Octave gives error if there is any problem in closing of a opened file.
186 File Operation
5.3.5 Print Output (sprintf)
It is similar to the printf except that it returns output as string. It automatically
reallocated the memory size to be fit for storing whole data. Syntax used for
this function is
✞
>>> sprintf (<conversion template >, <data >);
✌
✆
5.3.6 Output at Console (fprintf)
This function is used like
✞
1 >>> fprintf (<file_id >, <conversion template >, <data >);
✌
✆
It is similar to the printf function except that, the data is stored in stream
‘file id’ rather that putting it into stdout. If stream file id is not assigned, it is
displayed in stdout.
5.3.7 File Error (ferror)
ferror returns ‘1’ if an error has been encountered for the file ID and it returns
‘0’ otherwise.
✞
1 >>> f = fopen ("newfile .txt", "w");
>>> ferror(f);
3 >>> fclose(f);
✌
✆
5.3.8 File Report (freport)
freport() returns the all old files whose are opened recently and the mode of
their opening.
✞
1 >>> freport ()
✌
✆
It returns the all file list with access mode.
5.3.9 Delete a File (delete)
delete removes file from the disk. The path name of a file may be relative or
absolute.
✞
1 >>> delete("newfile.txt");
✌
✆
It shall remove the file “newfile.txt” from the disk.
5.3. I/O OPERATION 187
https://sites.google.com/view/arunumrao
5.3.10 Scan a Value (scanf)
scanf scans input stream according to the template string. The syntax is
✞
1 >>> [val , count] = scanf (<template >, <size >)
✌
✆
It returns the scanned value and number of bytes scanned in vector form.
5.3.11 Formatted Scanning (sscanf)
sscanf reads string in format based on template and copies it into output stream.
The syntax is
✞
1 >>> [val , count , errmsg , pos] =
>>> sscanf (<input >, <template >, <variable >)
✌
✆
It returns ‘true’ value if fscanf reads data successfully.
5.3.12 Rewind a Pointer (frewind)
frewind sets the file pointer to the beginning of the file, returning 0 for success,
and ‘-1’ if an error is encountered.
✞
>>> f=fopen(" myfile.txt","r");
2 >>> ipos = ftell(f) # Show the current position
>>> fgets(f,4); # Read the file four bytes
4 >>> ## Set the current position to four bytes from
>>> ## from begining of file .
6 >>> fseek(f,4, SEEK_SET );
>>> cpos = ftell(f) # Get the current file pointer.
8 >>> frewind(f) # Set pointer at the beginning of file .
>>> fpos = ftell(f) # Get the current position of file
pointer.
10 >>> fclose(f); # Close the file .
✌
✆
The output is
✞
ipos = = 0
cpos = = 4
fpos = = 0
✌
✆
5.3.13 Scan to Buffer (fscanf)
fscanf reads data from file stream and copies it into buffer stream. The syntax
is
188 File Operation
✞
1 >>> [val , count , errmsg] =
>>> fscanf (<in file id >, <template >, <variable >)
✌
✆
It returns ‘true’ value if fscanf reads data successfully.
5.3.14 Get Pointer Position (fseek)
A pointer is positioned at offset pointer from the beginning of a file during the
read mode of the file. Offset may be one of the predefined variables SEEK CUR
(current position), SEEK SET (beginning), or SEEK END (end of file) or strings
“cof”, “bof” or “eof”. If origin is omitted, SEEK SET is assumed by default.
Offset may be positive, negative, or zero but not all combinations of origin and
offset can be realized.
✞
>>> f=fopen("myfile.txt","r");
2 >>> ipos = ftell(f) # Show the current position
>>> fgets(f,4); # Read the file four bytes
4 >>> ## Set the current position after
>>> ## four bytes from begining of a file .
6 >>> fseek(f, 4, SEEK_SET );
>>> fpos = ftell(f) # Get the current position of file .
8 >>> fclose(f); # Close the file .
✌
✆
The output is
✞
ipos = 0
fpos = 4
✌
✆
5.3.15 Pointer Position (ftell)
ftell returns the current position of file pointer from the beginning of file. The
position of file pointer is updated when a file is either read or wrote. fseek also
updates the current position of file pointer.
✞
>>> f=fopen("myfile.txt","r");
2 >>> ftell(f)
>>> fclose(f);
✌
✆
The output is
✞
ans = 0
✌
✆
5.4 Reading Files
Here we will discuss the function those are used in reading files.
5.4. READING FILES 189
https://sites.google.com/view/arunumrao
5.4.1 Read File by Lines (fgetl)
fgetl is used to read characters from a file line by line. If length of characters
is given, then these amount of characters are read. If length of characters is
omitted then file is read until newline or EOF is not encountered.
✞
1 >>> f = fopen ("myfile.txt","r");
>>> dt = fgetl (f,3)
3 >>> fclose (f);
✌
✆
It reads only three chars of a line. In following example, Octave will read a
whole line.
✞
1 >>> f = fopen ("myfile.txt","r");
>>> dt = fgetl (f)
3 >>> fclose (f);
✌
✆
It reads whole line.
5.4.2 Read File by Characters (fgets)
It is similar to the fgetl. fgets is used to read characters from a file. If length
of characters is given, then these amount of characters are read. If length of
characters is omitted then file is read until newline or EOF is not encountered.
✞
1 >>> f = fopen ("myfile.txt","r");
>>> dt = fgets (f,3) # Number of chars are 3
3 >>> fclose (f);
✌
✆
It reads only three chars of a line.
✞
1 >>> f = fopen ("myfile.txt","r");
>>> dt = fgets (f) # Read whole line
3 >>> fclose (f);
✌
✆
It reads whole line.
5.4.3 Skip a Line (fskipl)
It reads and skips the number of lines as specified in the second argument of
the function. First argument to this function must be a file stream.
✞
1 >>> f = fopen ("myfile.txt","r");
>>> dt = fskipl (f,3) # skips 3 lines
3 >>> fclose (f);
✌
✆
If number of lines is not supplied, it skips only one line.
190 File Operation
✞
1 >>> f = fopen ("myfile.txt","r");
>>> dt = fskipl (f) # skips only one line
3 >>> fclose (f);
✌
✆
If number of line is ‘Inf’ then all the lines will be skipped until EOF is not
encountered.
✞
1 >>> f = fopen ("myfile.txt","r");
>>> dt = fskipl (f,Inf) # skips infinite lines
3 >>> fclose (f);
✌
✆
5.4.4 Read File in Binary (fread)
fread is used to read a file in binary format. The syntax of this function is
✞
1 >>> count = fread(
>>> <file_id >,
3 >>> <buffer_size >,
>>> <precision >,
5 >>> <skip >,
>>> <architecture >
7 >>> )
✌
✆
Here, ‘file id’ is id of previously opened file. Argument ‘buffer size’ tells that
how many binary data is to be read from stream file. The optional ‘buffer size’
values are given in the following table.
Buffer Size Description
Integer It is for specific number of data bytes.
Inf Read data as much as possible.
[r, Inf] Read data as much as possible, return-
ing a matrix with ‘r’ rows. If the
number of elements read is not an ex-
act multiple of ‘r’, the last column is
padded with zeros.
[r, c] Read data by r × c elements, returning
a matrix with ‘r’ rows. If the number of
elements read is not an exact multiple
of ‘r’, the last column is padded with
zeros.
5.4. READING FILES 191
https://sites.google.com/view/arunumrao
fread reads data equal to amount of ‘buffer size’ only and after that fread
process terminated. The optional argument ‘precision’ defines the size of ele-
ments to be read as one entity. The possible options are
Options Description
char Single character
schar Single signed character
uchar Single unsigned character
int Integer
uint Unsigned integer
int8 8-bit signed integer
int16 16-bit signed integer
int32 32-bit signed integer
int64 64-bit signed integer
uint8 8-bit unsigned integer
uint16 16-bit unsigned integer
uint32 32-bit unsigned integer
uint64 64-bit unsigned integer
single 32-bit floating point number
double 64-bit floating point number
long Long integer
ulong Unsigned long integer
float Single precision floating point number
The precision relation can be used as converter like
✞
1 >>> int16=>int32
✌
✆
This causes fread to read 16-bit integer values and return an array of 32-bit
integer values. The optional argument ‘skip’ specifies the number of bytes to
skip after each element (or the block of elements) is read. If it is not specified,
a value of 0 is assumed. If the final block read is not complete, the final skip
is omitted. The argument ‘architecture’ defines the data format. The optional
data formats are
192 File Operation
Data Format Description
native Data format of current machine
ieee-be IEEE big endian
ieee-le IEEE little endian
vaxd VAX D floating format
vaxg VAX G floating format
cray Cray floating format
The simple example of reading a file is by specific number of bytes.
✞
1 >>> f = fopen ("myfile.txt","r");
>>> ## + Read only one byte
3 >>> ## | + One char data at once
>>> dt = fread(f,1,"char ") # skips zero byte
5 >>> printf("%c",dt);
>>> fclose (f);
✌
✆
This will return the first byte as single character from the file that is open to
read. Read two bytes data with one ‘char’ size at once.
✞
>>> f = fopen ("myfile.txt","r");
2 >>> ## + Read only two bytes
>>> ## | + One char data at once
4 >>> dt = fread(f,2,"char "); # skips zero byte
>>> printf("%c",dt);
6 >>> fclose (f);
✌
✆
An example of reading a file is by specific number of bytes with ‘skip’1
optional
argument.
✞
>>> f = fopen ("myfile.txt","r");
2 >>> ## + Read only 5 bytes data
>>> ## | + One char data to be read at once
4 >>> dt = fread(f,5,"char " ,1) # skips one "char " after
>>> # reading one "char "
6 >>> printf("%c", dt);
>>> fclose (f);
✌
✆
1
If ‘precision’ is ‘char’ (say, it may be int or float as the case may be. It should be consider
as basic unit of data.) then one ‘char’ size data is read at once. If ‘precision’ is supplied as
‘2*char’ then ‘two char’ size data is read at once. ‘buffer size’ should be sufficiently large to
store the ‘precision’ size data. After each reading of group of ‘char’ elements, ‘skip’ times ‘char’
size data is skipped and again the ‘precision’ size data is read. fread reads until ‘buffer size’
is not filled by ‘precision’ data.
5.4. READING FILES 193
https://sites.google.com/view/arunumrao
To read whole file of large size, use while loop environment with smaller buffer
size. An example, with write and read functions, is given below
✞
1 >>> f = fopen ("myfile.txt","w");
>>> fwrite(f,"This is myfile.");
3 >>> fclose (f);
>>> f = fopen ("myfile.txt","r");
5 >>> while( !feof (f) )
>>> dt=fread (f,1,"char " ,1,"ieee -be")
7 >>> printf("%c",dt);
>>> endwhile
9 >>> fclose (f);
✌
✆
read function reads one character byte and skips next character byte. The actual
string (“This is my file.”) will appeared like
✞
Ti sm ie
✌
✆
Another example with element of two char size and one char size of skip
value is given below.
✞
1 >>> f = fopen ("myfile.txt","w");
>>> fwrite(f,"This is myfile.");
3 >>> fclose (f);
>>> f = fopen ("myfile.txt","r");
5 >>> while( !feof (f) )
>>> dt=fread (f,10,"2* char " ,1,"ieee -be");
7 >>> printf("%c",dt);
>>> endwhile
9 >>> fclose (f);
✌
✆
The output is
✞
Ths s y il.
✌
✆
5.4.5 CSV File Read (csvread)
Function csvread() is used to read comma separated value file. Syntax for this
function is
✞
1 >>> csvread(<file name >);
✌
✆
It read entire cvs file. To read specific range of data, dlmread() (delimiter read)
funciton is used.
✞
1 >>> dlmread(<file name >, <separator >, <from row >, <from
column >)
✌
✆
194 File Operation
To read ‘csv2.txt’, function is used as
✞
1 >>> csvread (’csv2 .txt’)
✌
✆
✞
ans =
0 0 0 0 0 0 0
0 0 3 6 9 12 15
0 0 5 10 15 20 25
0 0 7 14 21 28 35
0 0 11 22 33 44 55
✌
✆
✞
>>> dlmread (’csv2 .txt’,’,’ ,2,2)
✌
✆
✞
ans =
5 10 15 20 25
7 14 21 28 35
11 22 33 44 55
✌
✆
5.5 Writing Files
Writing contents into a file is performed by following methods.
5.5.1 Write Into File Unformatted (fputs)
fputs write a string to a file without formatting at the end of file. In other
words, it appends data into a file.
✞
>>> f = fopen ("myfile.txt","w");
2 >>> dt = fputs (f,"This is my file .")
>>> fclose (f);
✌
✆
On successful writing into a file, fputs returns ‘true’ value.
5.5.2 Write Into a File (fwrite)
fwrite puts contents on a file opened previously by fopen function. The syntax
of this function is
✞
1 >>> count = fwrite (
>>> <file_id >,
3 >>> <data >,
>>> <precision >,
5 >>> <skip >,
>>> <arch >
7 >>> )
✌
✆
5.5. WRITING FILES 195
https://sites.google.com/view/arunumrao
Here, argument ‘file id’ is the id of previously opened file into which ‘data’ is
to be written. ‘data’ is in binary format. The remaining arguments ‘precision’,
‘skip’, and ‘arch’ are optional. ‘count’ returns the number of bytes written
successfully into the file. The optional argument ‘precision’ defined the size of
elements to write as one entity. The possible options are
Options Description
char Single character
schar Single signed character
uchar Single unsigned character
int Integer
uint Unsigned integer
int8 8-bit signed integer
int16 16-bit signed integer
int32 32-bit signed integer
int64 64-bit signed integer
uint8 8-bit unsigned integer
uint16 16-bit unsigned integer
uint32 32-bit unsigned integer
uint64 64-bit unsigned integer
single 32-bit floating point number
double 64-bit floating point number
long Long integer
ulong Unsigned long integer
float Single precision floating point number
The precision relation can be used as converter like
✞
1 int16=>int32
✌
✆
This causes fwrite to write 16-bit integer values and return an array of 32-bit
integer values. The optional argument ‘skip’ specifies the number of bytes to
skip after each element (or block of elements) is write. If it is not specified, a
value of 0 is assumed. If the final block write is not complete, the final skip
is omitted. The argument ‘architecture’ defines the data format. The optional
data formats are
196 File Operation
Data Format Description
native Data format of current machine
ieee-be IEEE big endian
ieee-le IEEE little endian
vaxd VAX D floating format
vaxg VAX G floating format
cray Cray floating format
A working example is
✞
1 >>> f = fopen ("myfile.txt","w");
>>> dt = fwrite (f,"This is my file .") # skips zero byte
3 >>> fclose (f);
✌
✆
✞
This is my file
✌
✆
Use of fwrite with optional argument ‘precision’ is
✞
1 >>> f = fopen ("myfile.txt","w");
>>> dt = fwrite (f,"This is my file .","char ") # skips zero
byte
3 >>> fclose (f);
✌
✆
✞
This is my file
✌
✆
Use of fwrite with optional argument ‘precision’ and ‘skip’ is
✞
1 >>> f = fopen ("myfile.txt","w");
>>> dt = fwrite (f,"This is my file .","char " ,1) # skips one
byte
3 >>> fclose (f);
✌
✆
When we open the text file in which data is written we find that after each char
of the string, there is a null skipped character (one null byte)2
.
✞
T h i s i s m y f i l e .
✌
✆
An finally use of ‘architecture’ of the data type.
2
Space appears, when file is opened in notepad and unknown blocks are appeared in word-
pad.
5.5. WRITING FILES 197
https://sites.google.com/view/arunumrao
✞
1 >>> f = fopen ("myfile.txt","w");
>>> dt = fwrite (f,"This is my file .","char " ,1,"ieee -be")
3 >>> fclose (f);
✌
✆
✞
T h i s i s m y f i l e .
✌
✆
5.5.3 CSV Write (csvwrite)
CSV stands for Comma Separated Value. csv write data into comma separated
value file. Each data row is terminated by semi-colon ‘;’. Data in each row
separated by space. Data should be in matrix form. Its syntax is
✞
1 >>> csvwrite (<file name >, <data handle >);
✌
✆
✞
1 >>> m = [3 6 9 12 15; 5 10 15 20 25;
>>> 7 14 21 28 35; 11 22 33 44 55];
3 >>> csvwrite (’csv1 .txt’,m)
✌
✆
With column offsets the same function is used as
✞
1 >>> csvwrite (<file name >,
>>> <data handle >,
3 >>> <number of offset rows >,
>>> <number of offset cols >
5 >>> );
✌
✆
✞
1 >>> m = [3 6 9 12 15; 5 10 15 20 25;
>>> 7 14 21 28 35; 11 22 33 44 55];
3 >>> csvwrite (’csv2 .txt’,m,1,2)
✌
✆
To formatted write, CSV files are written with dlmwrite() function.
✞
1 >>> dlmwrite (
>>> <file name >,
3 >>> <data >,
>>> <row offset >,
5 >>> <col offset >,
>>> <key name >,
7 >>> <key value >,
>>> <options >
9 >>> )
✌
✆
1. append : It is used to select append mode on or off.
198 File Operation
2. delimiter : This key is used to controll the delimiter type. A delimiter
may be any alpha-numeric character or special symbol.
3. newline : The character(s) to use to separate each row. Three special
cases exist for this option. “unix” is changed into “n”, “pc” is changed
into “rn”, and “mac” is changed into “r”. Any other value is used
directly as the newline separator.
4. precision : It controls the significant digits.
✞
1 >>> m = [3 6 9 12 15; 5 10 15 20 25;
>>> 7 14 21 28 35; 11 22 33 44 55];
3 >>> dlmwrite ("dsv.tex", m, "delimiter ", "&", "newline ",
"n");
✌
✆
5.6 GUI Building
5.6.1 Getting Directory
The directory listing or choosing dialog is opened by uigetdir() function. Syn-
opsis of this function is used one of the listed below.
✞
1 >>> dirname = uigetdir ()
>>> dirname = uigetdir (<initial path >)
3 >>> dirname = uigetdir (<initial path >, <dialog name >)
✌
✆
In example below, a dialog is opened indicating to initial path to ‘/’. After
selection of a directory and choosing it, the function returns directory name to
function handler ‘dirname’. The directory name is displayed in output by disp()
function.
✞
1 >>> dirname = uigetdir ("/","Select Directory ");
>>> disp ( dirname);
✌
✆
✞
/mnt
✌
✆
5.6.2 Getting a File
A filtered file selection can be performed by uigetfile() function by using full
discription as shown below.
✞
1 >>> [filename , filepath , fileindex ] =
>>> uigetfile (
3 >>> <filtered extension >,
5.6. GUI BUILDING 199
https://sites.google.com/view/arunumrao
>>> <dialog name >,
5 >>> <default file >,
>>> "Position ",
7 >>> [px py],
>>> "MultiSelect ",
9 >>> <mode >
>>> )
✌
✆
We can omit one or all of the inputs but “position” & [px py] and “MultiSelect”
& mode shall be omitted in pair. Selected file name is returned to ‘filename’,
file path is returned to ‘filepath’. Each file in multimode selection is assigned a
unique id to ‘fileindex’.
✞
>>> [filename , filepath , fileindex ] = uigetfile ()
✌
✆
✞
filename = b.m
filepath = /home /arun /
fileindex = 1
✌
✆
5.6.3 Process Status
Durint the process, process progress can be visualized by wait bar. Wait bar in
Octave is activated by waitbar() function. Its synopsis is
✞
1 >>> <hid >= waitbar (
>>> <fract [0, 1]>,
3 >>> <message >,
>>> <figure property 1>,
5 >>> <property 1 value >,
>>> <figure property 2>,
7 >>> <property 2 value >,
>>> .................
9 >>> .................
>>> )
✌
✆
In this function, fraction value may be in range of [0, 1]. ‘message’ is the
description about the wait bar. Properties and their corresponding values are
used simultaneously.
✞
>>> <handle id >= waitbar (0.4,"% completed ");
✌
✆
Above method is used to open a waiting bar GUI and creation of its handle
id. To update a waiting bar with new fraction value, waitbar() function is used
again as given in following syntax.
✞
1 >>> waitbar(<fraction >, <handle id >, <message >);
✌
✆
200 File Operation
New fraction value shall be updated to the waiting bar identified by ‘handle id’.
✞
1 >>> h=waitbar (0,"% completed ");
>>> for(x =0:0.01:1)
3 >>> waitbar (x,h,"% completed ");
>>> endfor
✌
✆
5.6.4 Creating a Panel
uipanel() creates a panel for arranging of controls. Its syntax is
✞
>>> <hid > = uipanel (
2 >>> "parent",
>>> <parent figure handler >,
4 >>> <property 1>,
>>> <value for property 1>,
6 >>> ..............
>>> )
✌
✆
If ‘parent’ (value “parent”) is omitted then a uipanel for the current figure is
created. If no figure is available, a new figure is created first.
✞
1 >>> f = figure;
>>> p = uipanel (
3 >>> "title", #property title
>>> "Graphics Panel", #value for property title
5 >>> "position ", #property position
>>> [.25 .25 .5 .5] #value for property position
7 >>> );
>>> b1 = uicontrol (
9 >>> "parent", #parent window
>>> p, #figure handle
11 >>> "string", #control property string
>>> "A Button", #string value
13 >>> "position ", #position property
>>> [10 10 150 40] #position value
15 >>> );
>>> e1 = uicontrol (
17 >>> "parent", #parent window
>>> p, #figure handle
19 >>> "style", #control style
>>> "edit ", #control type edit
21 >>> "string", #control property string
>>> "An edit box", #string value
23 >>> "position ", #position property
>>> [10 50 150 40] #position value
25 >>> );
>>> c1 = uicontrol (
5.6. GUI BUILDING 201
https://sites.google.com/view/arunumrao
27 >>> "parent", #parent window
>>> p, #figure handle
29 >>> "style", #control style
>>> "checkbox ", #control type edit
31 >>> "string", #control property string
>>> "A check box", #string value
33 >>> "position ", #position property
>>> [10 100 150 40] #position value
35 >>> );
✌
✆
5.6.5 User Interactive Menu
The function uimenu is used to create user interactive menus. Its syntax is like
✞
1 >>> u = uimenu(h, <property >, <value >, ....)
✌
✆
If ‘h’ is omitted then a top-level menu for the current figure is created. If ‘h’ is
given then a submenu relative to ‘h’ is created. A top level menu should have
atleast one sub menu. The properties used with this function are “accelerator”
whose value is a string that is used as shortcut key with CTRL key. “callback”
property tells about the named function that will be executed if the correspond-
ing menu is interacted. The callback function may be either string name or an
object name, i.e. function name prefixed with‘@’ symbol without double quotes.
The callback function may be a cell array with function object name and its
arguments like {@f, arg1, arg2}. “foregroundcolor” for text colours. “label”
for menu label. The label value may have a ‘&’ symbol that can be marked
as accelerator. “position” for relative menu position.The entry with the lowest
value is at the first position starting from left or top. “separator” key has ”on”
or ”off” value. If enabled it draws a separator line above the current position.
It is ignored for top level entries.
✞
1 >>> f = figure;
>>> ## create top level menu in the context menu
3 >>> m1 = uimenu (f,"label","Add");
>>> ## Create sub menu under Add top level menu
5 >>> uimenu (m1 ,"label","Display
Add","callback ","disp (’Add ’)");
>>> ## create top level menu in the context menu
7 >>> m2 = uimenu (f,"label","Save ");
>>> ## Create sub menu under Add top level menu
9 >>> uimenu (m2 ,"label","Display
Save ","callback ","disp (’Save ’)");
✌
✆
202 File Operation
5.6.6 Create a Context Menu
Context menus are those menus which are appear on the right click over the fig-
ure where context menu is created. This menu does not appear either in toolbar
or in window. The construction of context menu is similar to the construction
of user interactive menus. The syntax of this function as given below.
✞
1 >>> <HUI > = uicontextmenu (
>>> <handle id >,
3 >>> <property 1>,
>>> <value of property 1>,
5 >>> <property 2>,
>>> <value of property 2>,
7 >>> ..........
>>> )
✌
✆
If ‘handle id’ is omitted, any change provided shall be applicable to the current
figure.
✞
>>> f = figure;
2 >>> c = uicontextmenu (f);
>>> % create menus in the context menu
4 >>>
m1=uimenu("parent",c," label","Add"," callback ","disp (’Add ’)");
>>>
m2=uimenu("parent",c," label","Save ","callback ","disp (’Save ’)");
6 >>> % set the context menu for the figure
>>> set (f, "uicontextmenu ", c);
✌
✆
5.6.7 Put String with Mouse
The function gtext places text on the current figure using the mouse. The string
passed to this function may be single cell value or cell array. A cell array string
is placed with every mouse click.
✞
1 >>> f = figure;
>>> function AddText(h, e, t)
3 >>> txt = inputdlg ("Enter string");
>>> h=gtext(txt);
5 >>> endfunction
>>> c = uicontextmenu (f);
7 >>> ## create menus in the context menu
>>> m1=uimenu("parent",c,
9 >>> "label","Add Text ",
>>> "callback " ,{@AddText ,f});
11 >>> set (f, "uicontextmenu ", c);
✌
✆
5.6. GUI BUILDING 203
https://sites.google.com/view/arunumrao
In Octave, we can listen mouse click and its location over figure by using ginput
function. It is used over graphics. We can use text function to put arbitrary
string at given location over plots. This function is used as shown below:
✞
1 >>> [x, y, btn] = ginput(<figure id >)
✌
✆
Here, x, y are coordinate values and btn is button pressed. btn value is 1 for left
click, 2 for middle mouse button press, 3 for right click and ascii code of any
other button pressed. It applications are given below:
✞
1 >>> f = figure;
>>> function AddText(h, e, t)
3 >>> txt = inputdlg ("Enter string");
>>> [x,y,b]= ginput(t);
5 >>> text (x, y, txt);
>>> endfunction
7 >>> c = uicontextmenu (f);
>>> ## create menus in the context menu
9 >>> m1=uimenu("parent",c,
>>> "label","Add Text ",
11 >>> "callback " ,{@AddText ,f});
>>> set (f, " uicontextmenu ", c);
✌
✆
5.6.8 Create Control
uicontrol() creates a control object and object id is returned as handler to it. It
is used to created simple interactive controls such as push button, check-boxes,
edit and list controls. If ‘parent’ is omitted then a uicontrol() is created for
current figure. If there is no figure then a new figure is created first. There are
following types of controls:
1. checkbox : It creates check box for on/off control.
2. edit : Creates editable text box for user input.
3. listbox : Creates a selectable list box like drop-down button.
4. popupmenu : Creates a pop up menu control which displays a list of
options for user selection.
5. pushbutton : Create a push button. Action related to push button is
performed by clicking on the button.
6. radiobutton : Create a radio button control intended to use exclusive
input in a group of radio button control.
7. slider : Creates a slider control that allows user to select an input value
by the relative position of the knob of the slider.
204 File Operation
8. text : Creates a static text control.
9. togglebutton : Creates a toggle button control that appears like a push
button. But it allows to select only one state.
These controls are invoked by style, i.e. these are values of style property.
Syntax for the function is
✞
>>> <hid > = uicontrol (
2 >>> <figure handle id >,
>>> <property 1>,
4 >>> <value for property 1>,
>>> ..............
6 >>> )
✌
✆
In the following lines of code, three user interactive controls are added into the
graphics pane.
✞
>>> f = figure;
2 >>> b1 = uicontrol (f, #figure handle
>>> "string", #control property string
4 >>> "A Button", #string value
>>> "position ", #position property
6 >>> [10 10 150 40] #position value
>>> );
8 >>> e1 = uicontrol (f, #figure handle
>>> "style", #control style
10 >>> "edit ", #control type edit
>>> "string", #control property string
12 >>> "An edit box", #string value
>>> "position ", #position property
14 >>> [10 50 150 40] #position value
>>> );
16 >>> c1 = uicontrol (f, #figure handle
>>> "style", #control style
18 >>> "checkbox ", #control type edit
>>> "string", #control property string
20 >>> "A check box", #string value
>>> "position ", #position property
22 >>> [10 100 150 40] #position value
>>> );
✌
✆
In the following figure, we have creates a slider and text control in the figure
window. The slider uses callback named function ‘cb’ to update the text control
string with the current value of slider. The controls first search callback function
in built-in function list, then in the same code script and finally the working
directory. If callback function is in same code script file, then prefer that it is
before the calling controls. In the following example, the callback function is in
the same code script.
5.6. GUI BUILDING 205
https://sites.google.com/view/arunumrao
✞
1 >>> function cb( )
>>> ## Copy the graphics data to handle g
3 >>> g = guidata (gcf);
>>> ## Get the slider value
5 >>> sv = get(g.s,’value’);
>>> ## Set the text value to slider value
7 >>> set(g.t,’string’,num2str (sv , "%10.5f"));
>>> endfunction
9 >>> ## Create a figure and handler object f
>>> f = figure(’position ’ ,[100 100 500
500],’units’,’pixels’);
11 >>> ## Retrieve the figure property structure of figure f.
>>> ## We can use gcf() function too but it returns figure
13 >>> ## data of current figure not of targeted figure
>>> h = get(f);
15 >>> ## Add a slider control . Add its handler to member s of
h
>>> h.s = uicontrol (’style’,’slider’,’position ’,
17 >>> [60 20 400 20], ’callback ’,@cb);
>>> ## The above callback function does not supplied
arguments
19 >>> ##
>>> ## Add a text control. Add its handler to member t of h
21 >>> h.t = uicontrol (’style’,’text ’,
>>> ’string ’, ’?????’,
23 >>> ’position ’ ,[60 50 400 20]) ;
>>> ## Bind the data of handler h into f
25 >>> guidata(f,h);
✌
✆
To allow the callback function with supplied arguments, the ‘callback’ key of
user interactive control object must have value in cell value structure, in which
first value is named or object callback function, and rest are arguments for the
callback function.
✞
1 >>> h.s = uicontrol (’style’,’slider’,’position ’,
>>> [60 20 400 20], ’callback ’,{@cb , 0.5});
✌
✆
But the structure of callback function being executed has two default parameters
and rest are argument parameters. The first parameter is source handle, i.e. the
user interactive control that is calling to this function, second is event, i.e. left
button click, middle button click, right button click, key press, button down or
button up etc., and rest are augment parameters. The argument parameters
may be other user interactive control handles, i.e. target control, too.
✞
>>> function cb(h, e, v)
2 >>> <function bod >
>>> endfunction
✌
✆
206 File Operation
The complete example for callback function is modified as given below:
✞
1 >>> function cb(h, e, v)
>>> g = guidata(gcf);
3 >>> sv = get(g.s,’value’);
>>> if(sv >v)
5 >>> set(g.t,’string ’,num2str(sv , "%10.5f"));
>>> endif
7 >>> endfunction
>>> f = figure(’position ’ ,[100 100 500
500],’units’,’pixels’);
9 >>> h = get(f);
>>> h.s = uicontrol (’style’,’slider’,’position ’,
11 >>> [60 20 400 20], ’callback ’,{@cb , 0.5});
>>> h.t = uicontrol (’style’,’text ’,
13 >>> ’string ’, ’?????’,
>>> ’position ’ ,[60 50 400 20]) ;
15 >>> guidata (f,h);
✌
✆
We can also pass the target object handle via uicontrol callback to the callback
function being executed. See the program given below:
✞
1 >>> function update(hs , e, ht)
>>> sv = get(hs ,’value’);
3 >>> set(ht ,’string’,num2str(sv , " %10.5f"));
>>> endfunction
5 >>> f = figure(’position ’ ,[100 100 500 500],
>>> ’units’,’pixels’);
7 >>> t1 = uicontrol (’style’,’text ’,
>>> ’string ’, ’?????’,
9 >>> ’position ’ ,[350 20 100 20]) ;
>>> s1 = uicontrol (’style’,’slider’,’position ’,
11 >>> [10 20 300 20], ’callback ’,{@update , t1});
>>> t2 = uicontrol (’style’,’text ’,
13 >>> ’string ’, ’?????’,
>>> ’position ’ ,[350 50 100 20]) ;
15 >>> s2 = uicontrol (’style’,’slider’,’position ’,
>>> [10 50 300 20], ’callback ’,{@update , t2});
✌
✆
Note that, the target handle that is being passed to callback function, must
be created before the calling of callback function as shown in above figure.
The basic callback functions that are available for all graphics objects. These
are CreateFcn that is called at the moment of the objects creation. Callbacks
that are added to CreateFcn later with the set function will never be executed.
DeleteFcn is called at the moment an object is deleted. ButtonDownFcn is
called if a mouse button is pressed while the pointer is over this object. There
are hundreds of the kye-value properties related to the user interactive controls
and toolbars. Each property can not be listed or explained here. We can get
5.6. GUI BUILDING 207
https://sites.google.com/view/arunumrao
the list of all associated properties to specific uicontrol by using get function as
shown below:
✞
>>> h = uicontrol ();
2 >>> get(h)
✌
✆
✞
ans =
scalar structure containing the fields:
beingdeleted = off
busyaction = queue
buttondownfcn = [](0 x0)
children = [](0 x1)
clipping = on
.................
units = pixels
value = 1
verticalalignment = middle
✌
✆
Be careful while applying key-value properties. A uicontrol has own specific
properties. Therefore before using a key-value property, first check it whether
it is member of the control or not by using get function as explained above.
Many properties has general meaning and purposes which are well known to
the learners, like font, font size, font weight, font type, foreground colour, back-
ground colour, color etc. For these properties the GNU-Octave help page can
be referred. Here, only important key-value properties are explained.
208 File Operation
Key Value & Description
accelerator It is character used with CTRL function. It works in menu control.
busyaction What to do when control is busy.
buttondownfcn What to do when middle or right mouse button pressed.
createfcn On action create function.
deletefcn On action delete function.
handlevisibility Visibility of handle. Default is on.
interruptible Whether control is interruptible or not. Default is on.
parent Graphics window level.
selected Control is selected by default.
visible Control is visible or not.
callback What shall be returned on action.
cdata Image data.
enable Control is enabled or disabled. Default is on.
max It controls the maximum value of the control.
min It controls the minimum value of the control.
sliderstep Number of steps in a slider.
string Name of control.
style Type of the control.
tooltipstring Returns the string when hover on the control.
units Measuring units of the graphical window and control tools.
value Returned value of the control.
Table 5.1: Description of properties most commonly used with uicontrol.
Example of Tooltip String A tooltip string is flashes when mouse pointer is
placed over the control tool. It is just like hint about the tool. See the example
given below:
✞
1 >>> h = uicontrol (’style’,’pushbutton ’,
>>> ’tooltipstring ’,’Click it’,
3 >>> ’string ’,’OK’);
✌
✆
5.6. GUI BUILDING 209
https://sites.google.com/view/arunumrao
Button Down Function A buttondownfcn is executed when middle or right
mouse button is pressed. Note that when left mouse button is pressed, then it
is called click.
✞
1 >>> h = uicontrol (’style’,’pushbutton ’,
>>> ’tooltipstring ’,’Click it’,
3 >>> ’buttondownfcn ’,"disp (’Pressed ’)",
>>> ’string’,’OK’);
✌
✆
✞
Pressed
Pressed
Pressed
Pressed
✌
✆
5.6.9 Figure Tool
uipushtool() creates a button that appear on a figure toolbar. The button is
created with a border that is shown when the user hovers over the button. Image
can set by using ‘cdata’ property. Syntax of this function is
✞
>>> <hui > = uipushtool (
2 >>> "parent",
>>> <property 1>,
4 >>> <value for property 1>,
>>> .............
6 >>> );
✌
✆
If “parent” is omitted then a user interactive push tool for the current figure
is created. If no figure is available, a new figure is created first. If a figure
is available, but does not contain a user interactive toolbar, a user interactive
toolbar will be created.
✞
>>> f = figure ("toolbar", "none ");
2 >>> % Create empty toolbar
>>> t = uitoolbar (f);
4 >>> % Create a 19 x19x3 black square
>>> img=zeros (19 ,19 ,3);
6 >>> % Add pushtool button to toolbar
>>> b = uipushtool (t, "cdata", img);
✌
✆
5.6.10 Toggle Tool
uitoggletool() creates a button that appear on a figure toolbar. The button
is created with a border that is shown when the user hovers over the button.
Image can set by using ‘cdata’ property. Syntax of this function is
210 File Operation
✞
1 >>> <hui > = uitoggletool (
>>> "parent",
3 >>> <property 1>,
>>> <value for property 1>,
5 >>> .............
>>> );
✌
✆
If “parent” is omitted then a toggle button for the current figure is created. If
no figure is available, a new figure is created first. If a figure is available, but
does not contain a toggle button, a toggle button will be created.
✞
>>> f = figure ("toolbar ", "none ");
2 >>> % create empty toolbar
>>> t = uitoolbar (f);
4 >>> % create a 19 x19x3 black square
>>> img=zeros (19 ,19 ,3);
6 >>> % add uitoggletool button to toolbar
>>> b = uitoggletool (t, "cdata", img);
✌
✆
5.6.11 Dialogue Box
Dialogues are those pop-up windows which are used for specific purposes, like
showing hints, showing errors, for users’ input etc. Followings are the different
dialogues which are implemented in Octave.
✞
1 >>> h = dialog (<property >, <value >, ...)
✌
✆
Creates a transparent dialogue window in which different controls can be put
by using uicontrol function. Error showing dialogue is created as shown below:
✞
1 >>> errordlg (<Error n instructions >, <dialogue title >);
✌
✆
The hint dialogue is shown below:
✞
1 >>> h = helpdlg (msg , title)
✌
✆
The input dialogue is define as shown below:
✞
1 >>> pr = {"W", "H"}; // field labels
>>> def = {"1", "2"}; // default values
3 >>> rc = [1 ,10; 2,20; 3 ,30];// rows and cols of the input
field
>>> dims = inputdlg (pr , "Enter Box Dimensions ", rc , def);
✌
✆
Question dialogue is used with three option buttons. The return value is button
name string.
5.6. GUI BUILDING 211
https://sites.google.com/view/arunumrao
✞
>>> btn = questdlg (msg , title , btn1 , btn2 , btn3 , default );
✌
✆
To highlight the dialogue’s default button, default value should be exactly the
button name. Message dialogue is created as shown below:
✞
1 >>> msgbox (msg , title , icon );
✌
✆
Warning dialog shows fancy warning.
✞
1 >>> warndlg ({ line 1, line 2}, title);
✌
✆
The listdlg, i.e. list dialogue shows a list of available options. On clicking over
OK button after selection of the options, it returns the index of selected option.
Index count in Octave is started from one to infinite.
✞
1 >>> myO = {"A", "B", "C"};
>>> [sel , ok] = listdlg ("ListString ", myO , options);
✌
✆
The first argument is compulsory. Options are provided in a group of key-value
options. The main options are “SelectionMode” key has “Single” or “Multiple’
option values. “ListSize” is a vector which two elements in which first is width
and second is height. Default initial values are provided with “InitialValue” key.
“Name” shows the name of dialogue. “OKString” and “CancelString” are used
for naming OK button and Cancel button respectively. “PromptString” key is
used to define the label of field. In all above dialogues, first argument is message
shown in dialogue body and second is dialogue title argument. Rest arguments
are specific inputs of the respective dialogue.
5.6.12 Tool Bar
uitoolbar() creates a user’s interactive toolbar and return a handle to it. A
uitoolbar displays uitoggletool and uipushtool buttons.
✞
>>> <hui > = uitoolbar (
2 >>> "parent",
>>> <parent handler >,
4 >>> <property 1>,
>>> <value for property 1>,
6 >>> .............
>>> );
✌
✆
If “parent” is omitted then a toolbar for the current figure is created. If no
figure is available, a new figure is created first. If a figure is available and it
does not contain a toolbar then a toolbar will be created.
✞
1 >>> f = figure ("toolbar", "none ");
>>> ## Create empty toolbar
212 File Operation
3 >>> t = uitoolbar (f);
✌
✆
5.6.13 Preferences
getpref returns the preference value corresponding to the named preference in a
group. setpref sets a preference to a given value in the named preference group.
addpref adds a preference and associated value to the named preference group.
rmpref remove the named preference from the preference group. ispref returns
true if the named preference exists in the preference group. prefdir return the
directory that contains the preferences for Octave. to change the preference
directory cd() function is used.
✞
1 >>> addpref (’mytoolbox ’,’version ’,’1.0 ’)
>>> getpref (’mytoolbox ’,’version ’)
3 >>> setpref (’mytoolbox ’,’version ’,’1.1 ’)
>>> getpref (’mytoolbox ’,’version ’)
5 >>> rmpref(’mytoolbox ’,’version ’)
>>> getpref (’mytoolbox ’,’version ’,’1.2 ’);
7 >>> getpref (’mytoolbox ’,’version ’)
✌
✆
✞
ans = 1.0
ans = 1.1
error: preference version does not exist in group mytoolbox
error: called from getpref at line .......
✌
✆
5.6.14 GUI Data
The function guidata() either used to get the current GUI data or used to update
the GUI data. It accepts one argument during querying about data and two
arguments during updating of figure data. First argument is figure handler and
second argument is data. The syntax for querying GUI data, the function is
used like
✞
>>> <data > = guidata(< figure handle >);
✌
✆
To set the user defined data, guidata() is used like
✞
1 >>> guidata (<figure handle >, <data >)
✌
✆
The GUI data is stored in the figure handle ‘h’. If ‘h’ is not a figure handle then
it’s parent figure will be used for storage. ‘data’ must be a single object which
means it is usually preferable for it to be a data container such as a cell array
or structure so that additional data items can be added easily. Before writing a
demo program, we will discuss about the working procedure of guidata function.
5.6. GUI BUILDING 213
https://sites.google.com/view/arunumrao
Let we have a figure that is created with figure function. The figure object is
assigned to the handler ‘h’.
✞
1 >>> f = figure ()
✌
✆
✞
f = 1
✌
✆
We can assign our own key value data to figure object. To do this, we must have
to first get the current graphic figure using get function. get function converts
scalar handler into structure.
✞
1 >>> f = figure ();
>>> h = get(f)
✌
✆
✞
h =
scalar structure containing the fields:
beingdeleted = off
busyaction = queue
buttondownfcn = [](0 x0)
children = [](0 x1)
.................
xdisplay =
xvisual =
xvisualmode = auto
✌
✆
The object fields or object members are created by using dot symbol as shown
in the following code lines. The object members created by dot symbol does
not appear in the figure until unless updated figure data is not copied into the
figure handler by using guidata function.
✞
1 >>> f = figure ();
>>> h = get(f);
3 >>> h.xrange = 1:10;
>>> h
✌
✆
✞
h =
scalar structure containing the fields:
beingdeleted = off
busyaction = queue
buttondownfcn = [](0 x0)
children = [](0 x1)
.................
wvisualmode = auto
xdisplay =
xvisual =
xvisualmode = auto
214 File Operation
xrange =
1 2 3 4 5 6 7 8 9 10
✌
✆
Note that, in the following code lines, which contains uicontrol functions, i.e.
✞
1 >>> f = figure ();
>>> h = get(f);
3 >>> h.a=uicontrol ()
>>> b = uicontrol (f)
5 >>> h
>>> f
✌
✆
have same effect in figure output. But, first control object ‘a’ is in same hierarchy
level as the object ‘h’ is and second control object ‘b’ is children of the parent
figure ‘f’.
✞
a = -2.8959
b = -4.8228
h =
scalar structure containing the fields:
beingdeleted = off
busyaction = queue
buttondownfcn = [](0 x0)
children = [](0 x0)
...........
xvisual =
xvisualmode = auto
a = -2.8959
f =
scalar structure containing the fields:
beingdeleted = off
busyaction = queue
buttondownfcn = [](0 x0)
children =
-4.8228
-3.5636
-1.3503
-2.8959
...........
xvisual =
xvisualmode = auto
✌
✆
Now a question is here, that what happens if we add axes into the figure as
its member value without calling get or gcf function. The answer is that, the
figure function returns the figure object id to its handler and it is a scalar value.
So, that structure (key-value arrangement) can not be added to it.
✞
1 >>> f = figure ();
>>> f.a=axes ()
5.6. GUI BUILDING 215
https://sites.google.com/view/arunumrao
3 >>> get(f)
✌
✆
✞
error: scalar cannot be indexed with .
error: assignment failed , or no method for ’scalar = scalar ’
f =
scalar structure containing the fields:
beingdeleted = off
busyaction = queue
buttondownfcn = [](0 x0)
children = [](0 x1)
.................
xvisual =
xvisualmode = auto
✌
✆
But if we add axes to current figure then Octave adds it as children of the parent
figure window.
✞
1 >>> f = figure ();
>>> a = axes ()
3 >>> get(f)
✌
✆
✞
h =
scalar structure containing the fields:
beingdeleted = off
busyaction = queue
buttondownfcn = [](0 x0)
children = -39.534
.................
xvisual =
xvisualmode = auto
✌
✆
Now, to access the axes properties, we have to use axes handler as shown in the
following codes:
✞
1 >>> f = figure ();
>>> a = axes ()
3 >>> get(a)
✌
✆
✞
ans =
scalar structure containing the fields:
beingdeleted = off
busyaction = queue
buttondownfcn = [](0 x0)
children = [](0 x1)
.................
zticklabel =
{
216 File Operation
[1,1] = 0
[1,2] = 0.2
[1,3] = 0.4
[1,4] = 0.6
[1,5] = 0.8
[1,6] = 1
}
zticklabelmode = auto
ztickmode = auto
✌
✆
The function guidata adds the current data of figure into the handler of the
figure. Following is an demo example that is using the GUI controls andguidata.
guidata is used to clean the figure for new plot. In my file ‘demo.m’ following
codes are written.
✞
>>> ## Create a figure with handler object f
2 >>> f = figure(’position ’ ,[100 100 500
500],’units’,’pixels’);
>>> ## Get the graphics structure of figure f
4 >>> h = get(f);
>>> ## Add axes data to member a of handler h
6 >>> h.a =
axes (’units’,’pixels’,’position ’ ,[60 ,100 ,400 ,300]) ;
>>> ## Add a slider control . Add its value to member s of h
8 >>> h.s = uicontrol (’style’,’slider’,’position ’,
>>> [60 20 400 20], ’callback ’,@cb);
10 >>> ## Create x value member into the handler h
>>> h.xrange = 1:100;
12 >>> ## Bind the window id to member f of handler h
>>> guidata (f,h);
✌
✆
The callback function is defined in file ‘cb.m’.
✞
1 >>> function cb( )
>>> ## Clean the figure
3 >>> g = guidata(gcf);
>>> ## Get the slider value
5 >>> sv = get(g.s,’value’);
>>> ## Plot the new function with new slider value
7 >>> ## and copy it into the axes object , i.e.
>>> ## its parent window is g.a
9 >>> plot (g.xrange , sv*sin(g.xrange),’parent’,g.a);
>>> endfunction
✌
✆
Both files are saved in same path and ‘demo.m’ is run from octave. On run of
GUI, we can redraw, plot for different slider value. Remember that the callback
function name and callback function file name, both must be same.
5.6. GUI BUILDING 217
https://sites.google.com/view/arunumrao
5.6.15 Handler GUI
The function guihandles() return a structure of object handles for the figure
associated with handle. Syntax of this function is
✞
>>> <hdata > = guihandles (< figure handle >)
✌
✆
5.6.16 Wait For Time
The function uiwait suspend program execution until the figure with handle
supplied handle is deleted or uiresume is not called. If there is no handle
supplied to this function, current figure is used by default. In case of invalid
figure handle or there is not current figure, this function returns immediately.
The minimum timeout value is 1. If timeout value is not specified, the program
execution is suspended indefinitely.
✞
1 >>> f = figure;
>>> function AddText(h, e, t)
3 >>> uiwait(t, 5); ## wait for 5 seconds
>>> txt = inputdlg ("Enter string");
5 >>> [x,y,b]= ginput(t);
>>> text (x, y, txt);
7 >>> endfunction
>>> c = uicontextmenu (f);
9 >>> ## create menus in the context menu
>>> m1=uimenu("parent",c,
11 >>> "label","Add Text ",
>>> "callback " ,{@AddText ,f});
13 >>> set (f, " uicontextmenu ", c);
✌
✆
We can use waitfor function too. This is different from the uiwait in sense
of conditions. The uiwait function suspends the program execute for a given
timeout interval instead of what is going in background. But waitfor suspends
program execution till the background conditions is not satisfied. We can update
background properties during the program suspension.
✞
1 >>> f = figure;
>>> function AddText(h, e, t)
3 >>> waitfor (t, "timeout ", 5); ## wait for 5 seconds
>>> txt = inputdlg ("Enter string");
5 >>> [x,y,b]= ginput(t);
>>> text (x, y, txt);
7 >>> endfunction
>>> c = uicontextmenu (f);
9 >>> ## create menus in the context menu
>>> m1=uimenu("parent",c,
218 Binary & Digital Operation
11 >>> "label","Add Text ",
>>> "callback " ,{@AddText ,f});
13 >>> set (f, "uicontextmenu ", c);
✌
✆
5.6.17 Resume Control
The function uiresume resumes the suspend program execution. The handle
supplied to this function should be same as the handle supplied to uiwait func-
tion. In case of no pending uiwait or invalid handle, this function does nothing.
✞
1 >>> function Suspend(h, e, t)
>>> uiwait(t, 10);## Wait for 10 seconds
3 >>> txt = inputdlg ("Enter string");
>>> [x,y,b]= ginput(t);
5 >>> text (x,y,txt);
>>> endfunction
7 >>> function Resume(h, e, t)
>>> uiresume (t); ## Resume immediately
9 >>> endfunction
>>> g = figure;
11 >>> c = uicontextmenu (g);
>>> ## create menus in the context menu
13 >>> m1=uimenu("parent",c,
>>> "label","Suspend",
15 >>> "callback " ,{@Suspend ,g});
>>> m2=uimenu("parent",c,
17 >>> "label","Resume",
>>> "callback " ,{@Resume ,g});
19 >>> set (g, "uicontextmenu ", c)
✌
✆
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao

More Related Content

What's hot

Διαγώνισμα κεφάλαιο 2ο Άλγεβρα Β΄ Λυκείου
Διαγώνισμα κεφάλαιο 2ο Άλγεβρα Β΄ ΛυκείουΔιαγώνισμα κεφάλαιο 2ο Άλγεβρα Β΄ Λυκείου
Διαγώνισμα κεφάλαιο 2ο Άλγεβρα Β΄ ΛυκείουΜάκης Χατζόπουλος
 
Linear algebra-Basis & Dimension
Linear algebra-Basis & DimensionLinear algebra-Basis & Dimension
Linear algebra-Basis & DimensionManikanta satyala
 
11 Κριτήρια Αξιολόγησης από το 1ο ΓΕΛ Βενετόκλειο Ρόδου
11 Κριτήρια Αξιολόγησης από το 1ο ΓΕΛ Βενετόκλειο Ρόδου11 Κριτήρια Αξιολόγησης από το 1ο ΓΕΛ Βενετόκλειο Ρόδου
11 Κριτήρια Αξιολόγησης από το 1ο ΓΕΛ Βενετόκλειο ΡόδουΜάκης Χατζόπουλος
 
Complex function
Complex functionComplex function
Complex functionShrey Patel
 
Linear dependence & independence vectors
Linear dependence & independence vectorsLinear dependence & independence vectors
Linear dependence & independence vectorsRakib Hossain
 
Τεστ στα ΕΠΑΛ στο 1ο κεφάλαιο Ανάλυσης
Τεστ στα ΕΠΑΛ στο 1ο κεφάλαιο ΑνάλυσηςΤεστ στα ΕΠΑΛ στο 1ο κεφάλαιο Ανάλυσης
Τεστ στα ΕΠΑΛ στο 1ο κεφάλαιο ΑνάλυσηςΜάκης Χατζόπουλος
 
Numarical values highlighted
Numarical values highlightedNumarical values highlighted
Numarical values highlightedAmanSaeed11
 
Second order homogeneous linear differential equations
Second order homogeneous linear differential equations Second order homogeneous linear differential equations
Second order homogeneous linear differential equations Viraj Patel
 
Μαθηματικά Επαναληπτικό διαγώνισμα μέχρι και κυρτότητα και σημεία καμπής
Μαθηματικά   Επαναληπτικό διαγώνισμα μέχρι και κυρτότητα και σημεία καμπήςΜαθηματικά   Επαναληπτικό διαγώνισμα μέχρι και κυρτότητα και σημεία καμπής
Μαθηματικά Επαναληπτικό διαγώνισμα μέχρι και κυρτότητα και σημεία καμπήςBillonious
 
Gradient divergence curl
Gradient divergence curlGradient divergence curl
Gradient divergence curlVikas Vikram
 
μαθηματικα & στοιχεια στατιστικης θεωρια - ζαμπελης
μαθηματικα & στοιχεια στατιστικης   θεωρια - ζαμπεληςμαθηματικα & στοιχεια στατιστικης   θεωρια - ζαμπελης
μαθηματικα & στοιχεια στατιστικης θεωρια - ζαμπεληςΣωκράτης Ρωμανίδης
 
Πέντε ασκήσεις χαρακτηριστικές στο σχήμα Horner
Πέντε ασκήσεις χαρακτηριστικές στο σχήμα HornerΠέντε ασκήσεις χαρακτηριστικές στο σχήμα Horner
Πέντε ασκήσεις χαρακτηριστικές στο σχήμα HornerΜάκης Χατζόπουλος
 
Matlab polynimials and curve fitting
Matlab polynimials and curve fittingMatlab polynimials and curve fitting
Matlab polynimials and curve fittingAmeen San
 
αποδείξεις στα μαθηματικά κατεύθυνσης γ λυκείου
αποδείξεις στα μαθηματικά  κατεύθυνσης γ λυκείουαποδείξεις στα μαθηματικά  κατεύθυνσης γ λυκείου
αποδείξεις στα μαθηματικά κατεύθυνσης γ λυκείουChristos Loizos
 
Διαγώνισμα 10- 2ο κεφάλαιο ΕΠΑ.Λ Γ Λυκείου
Διαγώνισμα 10- 2ο κεφάλαιο ΕΠΑ.Λ Γ ΛυκείουΔιαγώνισμα 10- 2ο κεφάλαιο ΕΠΑ.Λ Γ Λυκείου
Διαγώνισμα 10- 2ο κεφάλαιο ΕΠΑ.Λ Γ ΛυκείουΜάκης Χατζόπουλος
 

What's hot (20)

Vector Calculus.
Vector Calculus.Vector Calculus.
Vector Calculus.
 
Διαγώνισμα κεφάλαιο 2ο Άλγεβρα Β΄ Λυκείου
Διαγώνισμα κεφάλαιο 2ο Άλγεβρα Β΄ ΛυκείουΔιαγώνισμα κεφάλαιο 2ο Άλγεβρα Β΄ Λυκείου
Διαγώνισμα κεφάλαιο 2ο Άλγεβρα Β΄ Λυκείου
 
ΕΠΑΝΑΛΗΨΗ ΟΡΙΑ ΣΥΝΕΧΕΙΑ....
ΕΠΑΝΑΛΗΨΗ ΟΡΙΑ ΣΥΝΕΧΕΙΑ....ΕΠΑΝΑΛΗΨΗ ΟΡΙΑ ΣΥΝΕΧΕΙΑ....
ΕΠΑΝΑΛΗΨΗ ΟΡΙΑ ΣΥΝΕΧΕΙΑ....
 
Linear algebra-Basis & Dimension
Linear algebra-Basis & DimensionLinear algebra-Basis & Dimension
Linear algebra-Basis & Dimension
 
11 Κριτήρια Αξιολόγησης από το 1ο ΓΕΛ Βενετόκλειο Ρόδου
11 Κριτήρια Αξιολόγησης από το 1ο ΓΕΛ Βενετόκλειο Ρόδου11 Κριτήρια Αξιολόγησης από το 1ο ΓΕΛ Βενετόκλειο Ρόδου
11 Κριτήρια Αξιολόγησης από το 1ο ΓΕΛ Βενετόκλειο Ρόδου
 
Complex function
Complex functionComplex function
Complex function
 
Linear dependence & independence vectors
Linear dependence & independence vectorsLinear dependence & independence vectors
Linear dependence & independence vectors
 
Τεστ στα ΕΠΑΛ στο 1ο κεφάλαιο Ανάλυσης
Τεστ στα ΕΠΑΛ στο 1ο κεφάλαιο ΑνάλυσηςΤεστ στα ΕΠΑΛ στο 1ο κεφάλαιο Ανάλυσης
Τεστ στα ΕΠΑΛ στο 1ο κεφάλαιο Ανάλυσης
 
Numarical values highlighted
Numarical values highlightedNumarical values highlighted
Numarical values highlighted
 
Second order homogeneous linear differential equations
Second order homogeneous linear differential equations Second order homogeneous linear differential equations
Second order homogeneous linear differential equations
 
Μαθηματικά Επαναληπτικό διαγώνισμα μέχρι και κυρτότητα και σημεία καμπής
Μαθηματικά   Επαναληπτικό διαγώνισμα μέχρι και κυρτότητα και σημεία καμπήςΜαθηματικά   Επαναληπτικό διαγώνισμα μέχρι και κυρτότητα και σημεία καμπής
Μαθηματικά Επαναληπτικό διαγώνισμα μέχρι και κυρτότητα και σημεία καμπής
 
Gradient divergence curl
Gradient divergence curlGradient divergence curl
Gradient divergence curl
 
μαθηματικα & στοιχεια στατιστικης θεωρια - ζαμπελης
μαθηματικα & στοιχεια στατιστικης   θεωρια - ζαμπεληςμαθηματικα & στοιχεια στατιστικης   θεωρια - ζαμπελης
μαθηματικα & στοιχεια στατιστικης θεωρια - ζαμπελης
 
Πέντε ασκήσεις χαρακτηριστικές στο σχήμα Horner
Πέντε ασκήσεις χαρακτηριστικές στο σχήμα HornerΠέντε ασκήσεις χαρακτηριστικές στο σχήμα Horner
Πέντε ασκήσεις χαρακτηριστικές στο σχήμα Horner
 
Matlab polynimials and curve fitting
Matlab polynimials and curve fittingMatlab polynimials and curve fitting
Matlab polynimials and curve fitting
 
αποδείξεις στα μαθηματικά κατεύθυνσης γ λυκείου
αποδείξεις στα μαθηματικά  κατεύθυνσης γ λυκείουαποδείξεις στα μαθηματικά  κατεύθυνσης γ λυκείου
αποδείξεις στα μαθηματικά κατεύθυνσης γ λυκείου
 
Διαγώνισμα 10- 2ο κεφάλαιο ΕΠΑ.Λ Γ Λυκείου
Διαγώνισμα 10- 2ο κεφάλαιο ΕΠΑ.Λ Γ ΛυκείουΔιαγώνισμα 10- 2ο κεφάλαιο ΕΠΑ.Λ Γ Λυκείου
Διαγώνισμα 10- 2ο κεφάλαιο ΕΠΑ.Λ Γ Λυκείου
 
1551 limits and continuity
1551 limits and continuity1551 limits and continuity
1551 limits and continuity
 
7 functions
7   functions7   functions
7 functions
 
Es272 ch5b
Es272 ch5bEs272 ch5b
Es272 ch5b
 

Similar to Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao

1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdfvenud11
 
Programming in C Session 1
Programming in C Session 1Programming in C Session 1
Programming in C Session 1Prerna Sharma
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variablesSaurav Kumar
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and loopingChaAstillas
 
PE1 Module 4.ppt
PE1 Module 4.pptPE1 Module 4.ppt
PE1 Module 4.pptbalewayalew
 
Cordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to JavascriptCordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to JavascriptBinu Paul
 
Java script introducation & basics
Java script introducation & basicsJava script introducation & basics
Java script introducation & basicsH K
 
Fpga 06-data-types-system-tasks-compiler-directives
Fpga 06-data-types-system-tasks-compiler-directivesFpga 06-data-types-system-tasks-compiler-directives
Fpga 06-data-types-system-tasks-compiler-directivesMalik Tauqir Hasan
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operatorSAFFI Ud Din Ahmad
 
Python programing
Python programingPython programing
Python programinghamzagame
 
JavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfJavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfranjanadeore1
 

Similar to Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao (20)

Shell scripting
Shell scriptingShell scripting
Shell scripting
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdf
 
Programming in C Session 1
Programming in C Session 1Programming in C Session 1
Programming in C Session 1
 
Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variables
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 
PE1 Module 4.ppt
PE1 Module 4.pptPE1 Module 4.ppt
PE1 Module 4.ppt
 
Cordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to JavascriptCordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to Javascript
 
9-java language basics part3
9-java language basics part39-java language basics part3
9-java language basics part3
 
Java script introducation & basics
Java script introducation & basicsJava script introducation & basics
Java script introducation & basics
 
Fpga 06-data-types-system-tasks-compiler-directives
Fpga 06-data-types-system-tasks-compiler-directivesFpga 06-data-types-system-tasks-compiler-directives
Fpga 06-data-types-system-tasks-compiler-directives
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
 
Python_UNIT-I.pptx
Python_UNIT-I.pptxPython_UNIT-I.pptx
Python_UNIT-I.pptx
 
Preprocessors
PreprocessorsPreprocessors
Preprocessors
 
Python programing
Python programingPython programing
Python programing
 
Licão 13 functions
Licão 13 functionsLicão 13 functions
Licão 13 functions
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
 
JavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfJavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdf
 

More from ssuserd6b1fd

Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...ssuserd6b1fd
 
Decreasing increasing functions by arun umrao
Decreasing increasing functions by arun umraoDecreasing increasing functions by arun umrao
Decreasing increasing functions by arun umraossuserd6b1fd
 
Distribution of normal data understanding it numerical way by arun umrao
Distribution of normal data   understanding it numerical way by arun umraoDistribution of normal data   understanding it numerical way by arun umrao
Distribution of normal data understanding it numerical way by arun umraossuserd6b1fd
 
Decreasing and increasing functions by arun umrao
Decreasing and increasing functions by arun umraoDecreasing and increasing functions by arun umrao
Decreasing and increasing functions by arun umraossuserd6b1fd
 
What is meaning of epsilon and delta in limits of a function by Arun Umrao
What is meaning of epsilon and delta in limits of a function by Arun UmraoWhat is meaning of epsilon and delta in limits of a function by Arun Umrao
What is meaning of epsilon and delta in limits of a function by Arun Umraossuserd6b1fd
 
Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...
Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...
Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...ssuserd6b1fd
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...ssuserd6b1fd
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...ssuserd6b1fd
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...ssuserd6b1fd
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...ssuserd6b1fd
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...ssuserd6b1fd
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...ssuserd6b1fd
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...ssuserd6b1fd
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...ssuserd6b1fd
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...ssuserd6b1fd
 
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...ssuserd6b1fd
 
Work and Energy Notes by Arun Umrao
Work and Energy Notes by Arun UmraoWork and Energy Notes by Arun Umrao
Work and Energy Notes by Arun Umraossuserd6b1fd
 
Notes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
Notes of Units, Dimensions & Errors for IIT JEE by Arun UmraoNotes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
Notes of Units, Dimensions & Errors for IIT JEE by Arun Umraossuserd6b1fd
 
Physics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
Physics dictionary for CBSE, ISCE, Class X Students by Arun UmraoPhysics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
Physics dictionary for CBSE, ISCE, Class X Students by Arun Umraossuserd6b1fd
 
Java Programming Notes for Beginners by Arun Umrao
Java Programming Notes for Beginners by Arun UmraoJava Programming Notes for Beginners by Arun Umrao
Java Programming Notes for Beginners by Arun Umraossuserd6b1fd
 

More from ssuserd6b1fd (20)

Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
 
Decreasing increasing functions by arun umrao
Decreasing increasing functions by arun umraoDecreasing increasing functions by arun umrao
Decreasing increasing functions by arun umrao
 
Distribution of normal data understanding it numerical way by arun umrao
Distribution of normal data   understanding it numerical way by arun umraoDistribution of normal data   understanding it numerical way by arun umrao
Distribution of normal data understanding it numerical way by arun umrao
 
Decreasing and increasing functions by arun umrao
Decreasing and increasing functions by arun umraoDecreasing and increasing functions by arun umrao
Decreasing and increasing functions by arun umrao
 
What is meaning of epsilon and delta in limits of a function by Arun Umrao
What is meaning of epsilon and delta in limits of a function by Arun UmraoWhat is meaning of epsilon and delta in limits of a function by Arun Umrao
What is meaning of epsilon and delta in limits of a function by Arun Umrao
 
Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...
Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...
Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
 
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
 
Work and Energy Notes by Arun Umrao
Work and Energy Notes by Arun UmraoWork and Energy Notes by Arun Umrao
Work and Energy Notes by Arun Umrao
 
Notes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
Notes of Units, Dimensions & Errors for IIT JEE by Arun UmraoNotes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
Notes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
 
Physics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
Physics dictionary for CBSE, ISCE, Class X Students by Arun UmraoPhysics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
Physics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
 
Java Programming Notes for Beginners by Arun Umrao
Java Programming Notes for Beginners by Arun UmraoJava Programming Notes for Beginners by Arun Umrao
Java Programming Notes for Beginners by Arun Umrao
 

Recently uploaded

Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleCeline George
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 

Recently uploaded (20)

Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP Module
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 

Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by arun umrao

  • 1. 2.2. GLOBAL VARIABLE 151 https://sites.google.com/view/arunumrao ✞ x = { a = 1 a1 = 2 a2 = 3 } ✌ ✆ Since variable names may only contain letters, digits and underscores, genvar- name replaces any sequence of disallowed characters with an underscore. Also, variables may not begin with a digit; in this case an underscore is added before the variable name. Variable names beginning and ending with two underscores (“ ”) are valid but they are used internally by Octave and should generally be avoided, therefore genvarname will not generate such names. genvarname will also make sure that returned names do not clash with keywords such as “for” and “if”. A number will be appended if necessary. Note, however, that this does not include function names, such as “sin”. Such names should be included in avoid if necessary. 2.2 Global Variable A variable that has been declared as global may be accessed from within a function body without having to pass it as a formal parameter. A variable is set global by using global statement. Three variables ‘x’, ‘y’ and ‘z’ with ‘y’=1 are set as global variable in following example. ✞ >>> global x y=1 z; ✌ ✆ Global variable can be assigned only once. If same variable is required to use as global variable again, first use ✞ 1 >>> clear <global variable > ✌ ✆ or ✞ 1 >>> clear all ✌ ✆ A variable set global outside a function can not be assigned a value from the body of the function. But it just copy the value to global variable for use inside the function. ✞ 1 >>> global x; # global variable x >>> function f(x) 3 >>> x=1; # assigned value 1 withing function body >>> x # call variable within function body , prints 1 5 >>> endfunction >>> f() # call function 7 >>> x # call global variable , prints [](0 x0) for null value ✌ ✆
  • 2. 152 Variable ✞ x = 1 x = [](0 x0) ✌ ✆ 2.2.1 Is Variable Global isglobal is used to find whether a variable is global or not. It returns ‘true’ if variable is global otherwise ‘false’. ✞ >>> global x; # global variable x 2 >>> isglobal ("x") ✌ ✆ ✞ ans = 1 ✌ ✆ 2.3 Persistant Of a Variable A variable that has been declared persistent within a function will retain its con- tents in memory between subsequent calls to the same function. The difference between persistent variables and global variables is that persistent variables are local in scope to a particular function and are not visible elsewhere. ✞ 1 >>> global x=1; # global scope; can be called or copy anywhere >>> isglobal ("x") 3 >>> function f(y); >>> y=2; #local scope; within the function body 5 >>> endfunction ✌ ✆ ✞ ans = 1 ✌ ✆ 2.3.1 Clear Symbol From Table (clear) Delete the names matching the given patterns from the symbol table. The pattern may contain the following special characters: 1. ‘?’ : Match any single character. 2. ‘*’ : Match zero or more characters. 3. ‘[ ¡list¿ ]’ : Match the list of characters specified by list. If the first character is ‘!’ or ‘ˆ’ then matching of all characters is performed excepting those specified by a list. For example, the pattern [a-zA-Z]’ will match all lower and upper case alphabetic characters. For example
  • 3. 2.3. PERSISTANT OF A VARIABLE 153 https://sites.google.com/view/arunumrao ✞ 1 >>> clear foo b*r ✌ ✆ clears the name ‘foo’ and all names that begin with the letter ‘b’ and end with the letter ‘r’. If clear is called without any arguments, all user-defined variables (local and global) are cleared from the symbol table. 2.3.2 Show Files in Directory (what) what command is used to find all the Octave files in the directory. Syntax is ✞ 1 >>> what (<dir name >) ✌ ✆ If ‘dir name’ is empty, it returns the list of Octave files from the current path. 2.3.3 Function Name Type (which) It displays the type of each name. If name is defined from a function file, the full name of the file is also displayed. 2.3.4 Scope of Variable (who) who returns the scope of variable supplied by pattern. For example ✞ 1 >>> global x; >>> what ("x") ✌ ✆ ✞ Variables in the current scope: x ✌ ✆ Or ✞ >>> global x; 2 >>> who("global") ✌ ✆ ✞ Global variables : x ✌ ✆ 2.3.5 Exit From Loop (exist) exist returns whether the variable, function, file or director specifiend as argu- ment to the function are exist or not exist in the sytem. The syntax of this function is ✞ >>> exist(<name >, <type >) ✌ ✆
  • 4. 154 Functions There are four types of ‘type’ values. Type Description “var” Check only for variables “builtin” Check only for built-in functions “file” Check only for files “dir” Check only for directories Example is ✞ 1 >>> exist("meaning","var") ✌ ✆ ✞ ans = 0 ✌ ✆
  • 5. 3.1. FUNCTION 155 https://sites.google.com/view/arunumrao 3Functions Octave is written in ‘C’ and ‘C++’. Unlike ‘C++’ Octave does not required pre-definition of variable. Variables are automatically converted into integer, character etc forms according to the values passed to them. In other words, a value is assigned to a variable by juggling. If a variable ‘a’ is being added with ‘2’ then the variable ‘a’ would be considered as an integer type variable. But if it is to be added with ‘2.00202201220215’ then variable ‘a’ will be considered as an long type variable. In summary type of a variable is considered as it is being used. Each statement performed internally should be terminated by ‘;’. The statement whose result would be display in output window should not end with ‘;’. Statements, strings and variables are grouped inside a parenthesis brackets, ie ‘(’ ... ‘)’. Generally octave uses following code conventions. According to the Code Conventions for the Octave Programming Language it is recommended: 1. Start each statement on a new line. 2. Write no more than one simple statement per line. 3. Break compound statements over multiple lines. Following example uses two integers 2, 3 & ‘;’ and prints their result at output window. ✞ 1 /* Without pre -identification of * *variable and terminated by ’;’*/ 3 >>> a=2; /* Without pre -identification of * 5 *variable and terminated by ’;’*/ >>> b=3; 7 /* sum of two variables is called * *line does not terminated by ’;’*/ 9 >>> a+b ✌ ✆ ✞ ans = 5 ✌ ✆ If result of an operation is not assigned to a variable, then result is automatically assigned to ‘ans’ variable. 3.1 Function Function, in computer science is a set of instructions. This set of instruction is collectively called a script or code. Codes inside the function are not executed until unless function is not called. Some times more than one functions or com- mands are successively used for a specific purpose. The re-usability of these sets
  • 6. 156 Functions of functions or commands is very problematic. Hence these set of functions or commands are put inside a new function defined by user. Now this new defined function can be used as and when required. Octave is a strong language. It supports grouping of expressions. A group block started with reserved keyword and ended with the same keyword prefixed with ‘end’. ✞ 1 function f(x) <expression or codes > 3 endfunction ✌ ✆ ✞ 1 for <condition > <expression or codes > 3 endfor ✌ ✆ Octave has strong commenting support. Commenting are those lines which are inserted inside the program code to make it better understandable. Single line commenting is made with ‘#’ or ‘%’ symbols at the beginning of a line. These comments are just skipped by compilers and are not executed as part of the program. Entire block of lines can be commented by enclosing the lines between matching ‘#{ and ‘#} or ‘%{ and ‘%} markers. ✞ 1 #Beginning of a function function f(x) 3 <expression or codes > #{ 5 This block shall be executed when function f(x) is called. 7 #} endfunction ✌ ✆ 3.1.1 Defining A Functions In its simplest form, the definition of a function named name looks like this: ✞ >>> function <name > 2 >>> <body > >>> endfunction ✌ ✆ A function name should be a valid name. A valid function name contains letters, digits and underscores. A function name should not starting with a digit. In octave, the parameters are passed to a function as shown in following synopsis. ✞ 1 >>> function <name > (<arg -list >) >>> <body > 3 >>> endfunction ✌ ✆
  • 7. 3.1. FUNCTION 157 https://sites.google.com/view/arunumrao A function either modified to a predefined variable by changing its value or it returns a value as result. A function with single return value is defined as shown below. ✞ 1 >>> function <out var > = <name > (<arg -list >) >>> <body > 3 >>> endfunction ✌ ✆ A working example is given below: ✞ 1 >>> function o = myAvg (a, b) >>> o = (a+b)/2; 3 >>> endfunction ✌ ✆ If you want to define a function with output variables then be careful in writing the statement line in which output variable is being assigned the result. For example, in above example when we call the function with appropriate numbers of parameters, we see that the output is shown with default output variable, i.e. ans. ✞ 1 >>> myAvg (4, 5) ✌ ✆ ✞ ans = 4.5000 ✌ ✆ Output is not shown with out variable ‘o’ as we expected here. This is due to the termination of statement line with symbol ‘;’. Therefore, to assign the result to output variable, do not terminate the corresponding statement line by the line terminating symbol ‘;’ as shown in the following example. ✞ 1 >>> function o = myAvg (a, b) >>> o = (a+b)/2 3 >>> endfunction ✌ ✆ Now, call the function with appropriate numbers of parameters either by ter- minating it or by non terminating it. ✞ 1 >>> myAvg(4,5); ✌ ✆ ✞ o = 4.5000 ✌ ✆ ✞ 1 >>> myAvg(4,5) ✌ ✆ ✞ o = 4.5000 ans = 4.5000 ✌ ✆
  • 8. 158 Functions Now, here are two forms of outputs. If called a function with terminating symbol, then only user defined out variable is shown in the screen. Similarly, when called function is not terminated, then both user defined output variable and default output variable are shown in the screen. Her, the function can be called in its standard form too: ✞ >>> [a]= myAvg (4,5); ✌ ✆ ✞ o = 4.5000 ✌ ✆ ✞ 1 >>> [a]= myAvg (4,5) ✌ ✆ ✞ o = 4.5000 a = 4.5000 ✌ ✆ Arguments and their corresponding values may also be assigned in ‘argument list’ region. ✞ >>> function myFunc(msg="Hello!!!") 2 >>> printf(msg); >>> endfunction 4 >>> myFunc () ✌ ✆ ✞ Hello !!! ✌ ✆ The multiple output variables can be used in a function if output variables are arranged in a vector form. Each element has unique output value and they are independent of each other. ✞ 1 >>> function [<ret vector >] = <func name >(<args list >) >>> <contents of function i.e. body > 3 >>> endfunction ✌ ✆ Example is ✞ 1 >>> x=0; >>> function [y, z]= myFunc(x) 3 >>> y = x/10; >>> z = x*2; 5 >>> endfunction >>> [y,z]= myFunc (10) ✌ ✆ ✞ y = 1 z = 20 ✌ ✆
  • 9. 3.1. FUNCTION 159 https://sites.google.com/view/arunumrao If output variables are more than the return values in the function statements then output variables without return value in the statement of the body are assigned as null value. ✞ >>> x=0; 2 >>> function [y, z, t]= myFunc(x) >>> y = x/10; 4 >>> z = x*2; >>> # t is not assigned any return value 6 >>> endfunction >>> [y,z,t]= myFunc (10) ✌ ✆ ✞ y = 1 z = 20 t = [](0 x0) ✌ ✆ 3.1.2 Arguments Arguments are those values which are passed to a function. These arguments are used by the function itself for its internal operations. ✞ 1 >>> Func (<argument 1>, <argument 2>, ..., <argument n>) ✌ ✆ 3.1.3 Key Words Some function names are used by Software itself. These function names can not be redefined or reused by the program. Followings are the key words used by Octave itself. case catch classdef continue do else elseif end end try catch end unwind protect endclassdef endenumeration endevents endfor endfunction endif endmethods endparfor endproperties endswitch endwhile enumeration events for function global if methods otherwise parfor persistent properties return static switch try until unwind protect unwind protect cleanup while
  • 10. 160 Functions 3.1.4 Macro Macro is a group of two or more functions interdependent with each other to obtain a common goal. 3.1.5 Variables Variables are group of alphanumeric valid characters. Variables store numeric and non-numeric data that can be obtained by just calling the variable names. Each variable has its own scope that depends on the method of its definition. In Octave ‘type’ of variable is automatically assigned when it is assigned a value. 3.1.6 Number Format Octave uses double precision floating points as default number format upto five significant figures. This format can be changed by using function format with suitable options. Options are ‘short’, ‘long’, ’rat’, ‘hex’, ‘native-bit’ or ‘bank’. If format is invoked without any options, default format is restored. The options used have following meanings. Option Meaning short Prints five significant figures. long Prints fifteen significant figures. rat Prints rational form of numbers. hex Prints hexadecimal form of numbers. native-bit Prints binary form of numbers. bank Prints only two digits after decimal. ✞ 1 >>> format <type > ✌ ✆ For example ✞ 1 >>> format short; >>> pi ✌ ✆ ✞ ans = 3.1416 ✌ ✆
  • 11. 3.1. FUNCTION 161 https://sites.google.com/view/arunumrao ✞ >>> format long ; 2 >>> pi ✌ ✆ ✞ ans = 3.14159265358979 ✌ ✆ ✞ >>> format hex; 2 >>> pi ✌ ✆ ✞ ans = 400921fb 54442d18 ✌ ✆ 3.1.7 Number of Input Arguments (nargin) Octave has a table list called nargin that stores the variables of any size. Each time a function is called, nargin is automatically initialized to the number of arguments that have actually been passed to the function. ✞ >>> x=0; 2 >>> function [y, z] = myFunc(x) >>> y = x/10; 4 >>> z = nargin; >>> endfunction 6 >>> [y, z] = myFunc (10) ✌ ✆ ✞ y = 1 z = 1 ✌ ✆ nargin also tells about the number of arguments a function can accept. ✞ >>> x=0; 2 >>> function y=myFunc(x) >>> y = x/2; 4 >>> endfunction >>> function z=myFuncA(x,y) 6 >>> z = (x+y)/2; >>> endfunction 8 >>> nargin("myFunc") >>> nargin("myFuncA ") ✌ ✆ ✞ ans = 1 ans = 2 ✌ ✆
  • 12. 162 Functions 3.1.8 Number of Output Arguments (nargout) nargout tells about the number of return arguments present in the function definition. ✞ >>> x=0; 2 >>> function y = myFunc(x) >>> y = x/2; 4 >>> endfunction >>> function [z, t] = myFuncA(x, y) 6 >>> z = (x+y)/2; >>> endfunction 8 >>> nargout ("myFunc") >>> nargout ("myFuncA") ✌ ✆ ✞ ans = 1 ans = 2 ✌ ✆ 3.1.9 How to Use a Function (usage) If a function is not called properly, then this function tells about the proper use of the function. See in the following example: ✞ >>> x=0; 2 >>> function [y, z]= myFunc(x) >>> if (nargin != 1) 4 >>> usage ("myFunc (<vector >)"); >>> else 6 >>> y=x/10; >>> z = nargin; 8 >>> endif >>> endfunction 10 >>> [y,z]= myFunc() ✌ ✆ ✞ usage: myFunc (<vector >) ✌ ✆ 3.1.10 Error (error) This function is used to show the error occurs if any. ✞ 1 >>> x=0; >>> function y=myFunc(x) 3 >>> if (! isvector (x)) >>> y = x/2;
  • 13. 3.1. FUNCTION 163 https://sites.google.com/view/arunumrao 5 >>> else >>> error("x should not be a vector."); 7 >>> endif >>> endfunction 9 >>> myFunc ([10 ,20 ,30]) ✌ ✆ ✞ error: x should not be a vector. ✌ ✆ 3.1.11 Error Number (errno) It returns the current value of the system-dependent variable errno. ✞ 1 >>> err = errno () ✌ ✆ ‘err’ will be zero if there is no error otherwise error number if there is an error. 3.1.12 List of Error Numbers (errno list) errno list returns the list of errors and their corresponding numbers. ✞ 1 >>> errno_list ✌ ✆ ✞ ans = { E2BIG = 7 EACCES = 13 EAGAIN = 11 ...... EXDEV = 18 } ✌ ✆ 3.1.13 Last Error (lasterr) lasterr returns the error encountered to Octave most recently during the current session. ✞ >>> lasterr; ✌ ✆ 3.1.14 Last Warning (lastwarn) lastwarn returns the recent most warning shown by the Octave during the ses- sion. If there is not any warning during the session, it return empty result. ✞ 1 >>> lastwarn ; ✌ ✆
  • 14. 164 Functions 3.1.15 Variable Input Arguments (varargin) varargin appears as one argument of a function and it stores the number of arguments that can be accept by a function. varargin list is initialized auto- matically when a function is initialized. In other words, if user wants to supply variable numbers of arguments to a function then argument varargin should be used as a function argument. The syntax is ✞ 1 >>> function [<return value vector >] = <function name by user >( varargin ) >>> disp (varargin {i}) #ith element of variable argument 3 >>> endfunction ✌ ✆ Example is ✞ 1 >>> function myVarFunc (varargin ) >>> for i=1: length(varargin ) 3 >>> disp (varargin {i}); >>> disp ("n"); 5 >>> endfor >>> endfunction 7 >>> myVarFunc (10, 20, 30) >>> myVarFunc (10, 20, 30, 40) ✌ ✆ ✞ ans = 10 20 30 ans = 10 20 30 40 ✌ ✆ 3.1.16 Variable Output Arguments (varargout) varargout returns variable outputs. varargout list is initialized automatically when a function is initialized. The syntax is ✞ 1 >>> function varargout = <function name by user >( varargin ) >>> varargout {i}=i #ith element as ith out argument 3 >>> endfunction ✌ ✆ Example is
  • 15. 3.1. FUNCTION 165 https://sites.google.com/view/arunumrao ✞ 1 >>> function varargout = myVarFunc (varargin ) >>> for i=1: length(varargin ) 3 >>> varargout {i}= varargin {i}; >>> endfor 5 >>> endfunction >>> [a, b, c, d] = myVarFunc (10, 20, 30) ✌ ✆ ✞ ans = 10 20 30 error: element number 4 undefined in return list ✌ ✆ 3.1.17 Tilde ( ) is used in place of input argument name of a function to ignore the corre- sponding argument value and not stored it to any variable. Syntax is ✞ 1 >>> function [<ret vector >] = <func name >(~, <other arg(s) >) >>> val = <any other argument > 3 >>> endfunction ✌ ✆ The working example is ✞ 1 >>> x=0; >>> function myFunc(~, x) 3 >>> y = x+2; >>> endfunction 5 >>> myFunc(10, 20) ✌ ✆ ✞ ans = 22 ✌ ✆ The value of nargin is not affected by using this declaration. 3.1.18 Whether Argument is Out Type (isargout) isargout returns ‘true’ if string is a valid out argument otherwise returns ‘false’. ✞ 1 >>> x=0; >>> function y = myFunc(~, x) 3 >>> isargout (1) # true as y is out argument >>> isargout (2) # false as there is no 5 >>> # second out argument >>> y=x+2; 7 >>> endfunction >>> myFunc(10, 20) ✌ ✆
  • 16. 166 Functions ✞ ans = 1 % only one out argument ‘y’ ans = 0 % No second argument ans = 22 ✌ ✆ 3.1.19 Return Command (return) When Octave encounters the keyword return inside a function or script, it re- turns control to the caller immediately. At the top level, the return statement is ignored. A return statement is assumed at the end of every function definition. ✞ 1 >>> x=0, y=0; >>> function z= myFunc(x,y) 3 >>> for i=1:x >>> if(i==y) 5 >>> z=i; >>> return; 7 >>> endif >>> endfor 9 >>> endfunction >>> myFunc (30, 15) ✌ ✆ ✞ ans = 15 ✌ ✆ 3.1.20 Add Environmental Path (addpath) It add named directories to the function’s search path. Search paths are those directories where a function looks-up for the files. ✞ 1 >>> addpath (<directory path >) ✌ ✆ Example is ✞ 1 >>> path = addpath("/") ✌ ✆ It returns all Octave’s search paths. 3.1.21 Remove Environmental Path (rmpath) It removes named directories from the function’s search path. ✞ 1 >>> rmpath(<directory path >) ✌ ✆
  • 17. 3.1. FUNCTION 167 https://sites.google.com/view/arunumrao 3.1.22 Lock A Function (mlock) Locks the current function into memory so that it can’t be clear. mlock must be called from the body of the function. Right order of syntax is ✞ 1 >>> function myFuncA () >>> mlock() # always called from the function body 3 >>> endfunction >>> myFuncA () ✌ ✆ 3.1.23 Unlock A Function (munlock) To unlock a locked function, munlock is used. Its argument is a function name that is previously locked. munlock can be called from inside or outside of the function body. From inside the body ✞ >>> function myFuncA () 2 >>> mlock() >>> munlock () # call from the body of function 4 >>> endfunction >>> myFuncA () 6 >>> mislocked ("myFuncA") ✌ ✆ ✞ ans = 0 ✌ ✆ From outside the function body, this function needs input argument which is name of the function being unlocked. ✞ 1 >>> function myFuncA () >>> mlock() 3 >>> endfunction >>> myFuncA () 5 >>> munlock(" myFuncA") # call from outside of >>> # the body of function 7 >>> mislocked ("myFuncA") ✌ ✆ ✞ ans = 0 ✌ ✆ 3.1.24 Whether A Function is Locked (mislocked) It returns ‘true’ if the current function or the function supplied as argument is locked otherwise returns ‘false’. mislocked may be called from the body of function or outside the function.
  • 18. 168 Functions ✞ 1 >>> function myFuncA () >>> mlock() 3 >>> mislocked () # call from the body of function >>> endfunction 5 >>> myFuncA () ✌ ✆ ✞ ans = 1 ✌ ✆ From outside the function body, this function must be supplied name of function that is being checked whether it is locked or not. ✞ 1 >>> function myFuncA () >>> mlock() 3 >>> endfunction >>> myFuncA () 5 >>> mislocked ("myFuncA ") ✌ ✆ ✞ ans = 1 ✌ ✆ 3.2 Function Handler A function handle point to another inbuilt or user define function. The function object is accesses by prefixing ‘@’ symbol. Without ‘@’ symbol, the value is treated as string. The syntax is ✞ 1 >>> h = @<function name > ✌ ✆ Example is ✞ 1 >>> f = @sin ; >>> f(pi /3) ✌ ✆ ✞ ans = 0.86603 ✌ ✆ 3.2.1 Whether Argument is Function Handle (is function handle) It return ‘true’ if argument is a function handle. ✞ 1 >>> f = @sin ; >>> is_function_handle (f) ✌ ✆ ✞ ans = 1 ✌ ✆
  • 19. 3.2. FUNCTION HANDLER 169 https://sites.google.com/view/arunumrao 3.2.2 Anonymous Functions An anonymous function has no name, but it is identified by its handle which assigned the anonymous function’s object address. An anonymous function can be defined by using syntax like ✞ 1 >>> f = @(<argument list >) <expression > ✌ ✆ Example is ✞ 1 >>> f = @(x) x.^2; >>> f(2) ✌ ✆ ✞ ans = 4 ✌ ✆ 3.2.3 Sub Functions A function has a complete body and it may call another functions. When a function is called inside the body of main function then called function is known as sub function of the main function. ✞ 1 >>> function myFuncA () >>> printf ("in myFuncA , calling myFuncB n"); 3 >>> myFuncB (); >>> endfunction 5 >>> function myFuncB () >>> printf ("in myFuncB , calling myFuncC n"); 7 >>> myFuncC (); >>> endfunction 9 >>> function myFuncC () >>> printf ("in myFuncC n"); 11 >>> endfunction ✌ ✆ For the function ‘myFuncA’, function ‘myFuncB’ is a sub function while for ‘my- FuncB’ function ‘myFuncC’ is sub function. Sub functions are used to carryout short computations for the main function. 3.2.4 Nested Function A function within another function is called nested functions. In the following example, ‘myFuncA’ is nested function for the outer function ‘myFunc’. ✞ 1 >>> function y=myFunc() >>> x=10; 3 >>> myFuncA (); >>> y=x;
  • 20. 170 Conditional Function 5 >>> function myFuncA () >>> x=20; 7 >>> endfunction >>> endfunction 9 >>> myFunc () ✌ ✆ ✞ ans = 20 ✌ ✆
  • 21. 4.1. LOOP CONDITION 171 https://sites.google.com/view/arunumrao 4Conditional Function Conditional operators are those functions which allow to execute specific region if certain conditions are met. There are two categories of conditional functions. Loop conditions and switch conditions. 4.1 Loop Condition Loop condition provides to execute same region again and again until specific condition is not met to exit the loop. Followings are the loop conditions. 4.1.1 For Condition (for) for statement is used to iterate the code body like the syntax ✞ 1 >>> for variable =initial:incr :limit >>> .... code statement .... 3 >>> endfor ✌ ✆ for statement is useful when initialized variable is to be used in statement. Variable is started with ‘initial’ value. After each iteration, variable is increased by increment ‘incr’. When variable superseded its ‘limit’, for statement seizes to execute codes. ✞ 1 >>> for i=0:2:10 >>> i 3 >>> endfor ✌ ✆ ✞ i = 0 i = 2 i = 4 i = 6 i = 8 i = 10 ✌ ✆ It will remember that each for statement must be closed by endfor. for state- ment can also be used like ✞ for variable = initial:limit 2 .... code body .... endfor ✌ ✆ In this type of expression of for statement, variable is increased by ‘one’ after each iteration.
  • 22. 172 Conditional Function ✞ 1 >>> for i=1:5 >>> i 3 >>> endfor ✌ ✆ ✞ i = 1 i = 2 i = 3 i = 4 i = 5 ✌ ✆ for statement also accepts the array elements for performing loop. ✞ 1 >>> for i={1,2, "A"} >>> i 3 >>> endfor ✌ ✆ ✞ i = { [1,1] = 1 } i = { [1,1] = 2 } i = { [1,1] = A } ✌ ✆ Here each [1,1] represents the rows and columns of each array element. A two dimensional array may also be used. ✞ >>> for i={1 ,2;"A","B"} 2 >>> i >>> endfor ✌ ✆ ✞ i = { [1,1] = 1 [2,1] = A } i = { [1,1] = 2 [2,1] = B } ✌ ✆
  • 23. 4.1. LOOP CONDITION 173 https://sites.google.com/view/arunumrao for statement and matrix expression may be correlated with each other. The method is given in following example. ✞ >>> for i=[1 ,2;3 ,4] 2 >>> i >>> endfor ✌ ✆ ✞ i = 1 3 i = 2 4 ✌ ✆ In above procedure, columns are executed in one iteration. An key-value relation of for statement is ✞ >>> x.a=1; # Set key ’a’ for value ’1’ 2 >>> x.b=2; # Set key ’b’ for value ’2’ >>> ## Call value and key from variable ’x’ in matrix form 4 >>> for [val , key]=x; >>> key # Print key 6 >>> val # Print value >>> endfor # End for loop ✌ ✆ ✞ key = a val = 1 key = b val = 2 ✌ ✆ 4.1.2 While Condition (while) while statement performs looping until the condition is met. ✞ >>> i=1; 2 >>> while(i<10) >>> i 4 >>> i++; >>> endwhile ✌ ✆ ✞ i = 3 i = 4 i = 5 i = 6 i = 7
  • 24. 174 Conditional Function i = 8 i = 9 ✌ ✆ Each while statement must be closed with endwhile. 4.1.3 Do-until Condition (do ... until) The do-until statement is similar to the while statement, except that it re- peatedly executes a statement until a condition becomes true. The test of the condition is at the end of the loop, so the body of the loop is always executed at least once. ✞ 1 >>> i=1; >>> do 3 >>> i >>> i++; 5 >>> until(i==10) ✌ ✆ ✞ i = 1 i = 2 i = 3 i = 4 i = 5 i = 6 i = 7 i = 8 i = 9 ✌ ✆ 4.2 Switch Condition (switch) Switch conditions has two results, (i) if the condition is ‘true’ and (ii) if the condition is ‘false’. Hence the code bodies are executed if condition is either ‘true’ or ‘false’. 4.2.1 If Condition (if) if condition is used to execute enclosed codes if certain conditions are met as desired by the user. ✞ 1 >>> i=1; >>> if(i<2) # If this statement is true 3 >>> disp ("Variable ’i’ is less than two"); >>> endif ✌ ✆ ✞ Variable ’i’ is less than two ✌ ✆
  • 25. 4.2. SWITCH CONDITION (SWITCH) 175 https://sites.google.com/view/arunumrao Each if statement opened must be closed with endif. else statement can also be used for false condition, if there may be. ✞ 1 >>> i=3; >>> if(i<2) # If this statement is true 3 >>> disp ("Variable ’i’ is less than two"); >>> else 5 >>> disp ("Variable ’i’ is greater than two"); >>> endif ✌ ✆ ✞ Variable ’i’ is greater than two ✌ ✆ 4.2.2 Break Command (break) break command stops the current process of loop and allow exit from the loop. break command is always used inside a loop. Example is ✞ 1 >>> for(i=1:1:10) >>> if(i>5) 3 >>> disp ("Looped by five times") >>> break; 5 >>> endif >>> disp (i) 7 >>> endfor ✌ ✆ ✞ 1 2 3 4 5 Looped by five times ✌ ✆ 4.2.3 Continue Command (continue) The continue command, like break, can be used only inside the while, do-until, or for loops. It skips over the rest of the loop body, causing the next cycle around the loop to begin immediately. Contrast this with break, which jumps out of the loop altogether. The syntax is ✞ >>> for x = <value > 2 >>> if (<condition >) >>> continue ; 4 >>> endif >>> printf (<print statements >); 6 >>> endfor ✌ ✆
  • 26. 176 Conditional Function Example is ✞ >>> for x = 1:5 2 >>> if (x==3) >>> continue ; 4 >>> endif >>> printf ("%dn",x); 6 >>> endfor ✌ ✆ ✞ 1 2 % x=3 is skipped due to continue command 4 5 ✌ ✆ 4.2.4 Try-Catch Statement try ... catch statement is used within loop environment. The syntax of this function is ✞ 1 >>> try >>> <try statement > 3 >>> catch >>> <catch statement > 5 >>> end_try_catch ✌ ✆ Each try ... catch must be closed by using end try catch keyword. Example is ✞ 1 >>> x=1; >>> for(x =1:10) 3 >>> try >>> if(x<5) 5 >>> x >>> endif 7 >>> catch >>> x 9 >>> end_try_catch >>> endfor ✌ ✆ try keyword tries to execute the subsequent codes which are within its scope. If codes are successfully executed then it returns nothing. If there is error during the execution of codes, it throws an error which is captured through the catch. try ... catch statement has advantage that it does not exit the program. It either shows default errors if it occurs during the code execution or simply skips the current loop iteration. See following two examples:
  • 27. 4.2. SWITCH CONDITION (SWITCH) 177 https://sites.google.com/view/arunumrao ✞ >>> x=1; 2 >>> for(x=1:10) >>> fread("a","r") 4 >>> endfor ✌ ✆ ✞ error: fread: invalid stream number = -1 ✌ ✆ Above example shows an error of invalid stream number as the file being opened is not present in the default temporary directory of Octave. Again the modified example is ✞ 1 >>> x=1; >>> for(x=1:10) 3 >>> try >>> fread("a","r") 5 >>> catch >>> end_try_catch 7 >>> endfor ✌ ✆ It does not shows any error or warning.
  • 29. 5.1. PC INFO (INFO) 179 https://sites.google.com/view/arunumrao 5File Operation 5.1 PC Info (info) Octave provides expanded environment and application of C like languages. It means, with Octave, we not only do computations but we can also access the files/memory of the host system. The file operation capability of Octave is similar to the C programming languages. In the following sections, we shall discuss about the read/write/update the files/directories of host system. 5.1.1 System Architecture (computer) It returns the information regarding the architecture of the computer system under which it was compiled. ✞ 1 >>> computer () ✌ ✆ ✞ i686-w64- mingw32 ✌ ✆ 5.1.2 Is Windows (ispc) It returns true if Octave is running on windows operating system. ✞ 1 >>> ispc () ✌ ✆ ✞ ans = 1 ✌ ✆ 5.1.3 Is Linux (isunix) It returns true if Octave is running on unix operating system otherwise it returns false. ✞ 1 >>> isunix() ✌ ✆ ✞ ans = 0 ✌ ✆
  • 30. 180 File Operation 5.1.4 Parent Machine (isdeployed) isdeployed checks whether Octave is running in same machine in which it is compile or not. If it is running in other machine, it returns ‘true’ value otherwise ‘false’ value. ✞ 1 >>> isdeployed () ✌ ✆ ✞ ans = 0 ✌ ✆ 5.1.5 Version (version) It returns the version of the Octave. ✞ 1 >>> v = version () ✌ ✆ 5.1.6 License (license) It returns the license of the Octave. ✞ 1 >>> v = license () ✌ ✆ ✞ v = GNU General Public License ✌ ✆ 5.2 Directory Management In this section we will discuss about the creation of directory, files, their access- ing, reading, renaming, deletion etc. 5.2.1 Make a Dir (mkdir) mkdir creates a directory in the current path used by Octave. If directory is present then it just returns true value. If a directory is successfully created, it returns true value otherwise false value. Syntax is ✞ 1 >>> [STATUS , MSG , MSGID] = mkdir (PARENT , DIR) ✌ ✆ Example of creating a directory “a” is ✞ 1 >>> mkdir("a"); ✌ ✆ The output is
  • 31. 5.2. DIRECTORY MANAGEMENT 181 https://sites.google.com/view/arunumrao ✞ ans = 1 ✌ ✆ 5.2.2 List Directory (ls) It returns the list of all directories present in the current working directory. 5.2.3 Change Directory (cd) It changes the current directory to the new location as specified by the directory path of this command. Path may be either relative or absolute. The syntax of this function is ✞ 1 >>> cd <dir name > >>> cd(<dir name as string >) ✌ ✆ Another method to change the directory is chdir. ✞ >>> chdir(<dir path >) ✌ ✆ 5.2.4 Directory (dir) dir returns the all files and sub directories present in the current directory. ✞ 1 >>> dir() ✌ ✆ 5.2.5 Is Directory (isdir) isdir returns ‘true’ if relative path or absolute path is a directory otherwise returns ‘false’. ✞ 1 >>> isdir(<relative or absolute file path >) ✌ ✆ 5.2.6 Remove Directory (rmdir) rmdir removes the directory whose name is supplied as argument to this func- tion. It also removes sub directories and files inside the target directory. ✞ 1 >>> rmdir(<relative or absolute file path >) ✌ ✆
  • 32. 182 File Operation 5.2.7 Read Directory (readdir) readdir reads the directory whose name is supplied as argument to the function. Syntax is given below ✞ 1 >>> [files , error , msg] = readdir (< directory name >) ✌ ✆ It returns three output handlers. First array is the list of all files inside the directory. Second array is error type encounters while Octave tries to read the directory and third is message returned by Octave when it read directory successfully or not. 5.2.8 Temporary Directory (tempdir) It returns the path of temporary directory used by the Octave for temporary operation/execution. In this directory, temporary files are used for internal ap- plication of Octave. When the session or application of Octave ended, temporary files are removed from the directory. This function is used like ✞ 1 >>> tempdir ✌ ✆ Another method is ✞ 1 >>> tempdir () ✌ ✆ ✞ ans = C: DOCUME ~1 ADMINI ~1 LOCALS ~1 Temp ✌ ✆ 5.2.9 Temporary Name (tempname) It returns the name of temporary directory used by the Octave for temporary operation/execution. User can set another directory as temporary directory as and when required. Use this function ✞ 1 >>> tempname ✌ ✆ ✞ 1 >>> tempname () ✌ ✆ ✞ ans = C: DOCUME ~1 ADMINI ~1 LOCALS ~1 Temp oct -2 ✌ ✆
  • 33. 5.2. DIRECTORY MANAGEMENT 183 https://sites.google.com/view/arunumrao 5.2.10 Attribute of File (fileattrib) It returns the attributes of a file supplied as argument to the function. The syntax of this function is ✞ 1 >>> [status , result , msgid] = fileattrib (<file path >) ✌ ✆ If Octave is successful in getting of attribute ‘status’ is ‘1’. ‘result’ returns arrays of the result on successful retrieval of attributes. ‘msgid’ is id of message shown by Octave if any. 5.2.11 File Marker (filemarker) It is used to find or set the character used to separate file-name from the the sub-function names contained within the file. The syntax is ✞ 1 >>> val = filemarker () # for query >>> filemarker (<new val >, " local") # for set the character ✌ ✆ 5.2.12 File Parts (fileparts) fileparts returns the directory in which file is placed, name of file, extension of file and version. Syntax is ✞ >>> [dir , name , ext , ver] = fileparts (<file name >) ✌ ✆ 5.2.13 File Separator (filesep) filesep returns the separator of directory/file in path name. It may be forward slash or backward slash. File separator depends on the Operating System used by Octave. ✞ 1 >>> filesep ✌ ✆ ✞ ans = ✌ ✆ 5.2.14 Copy File (copyfile) copyfile copies a file with another name. The path of directory may be relative or absolute. Syntax is ✞ 1 >>> [status , msg , msgid] = >>> copyfile (<source file >, <dest file >) ✌ ✆
  • 34. 184 File Operation If the destination file exists, it overwrites the destination file by the file being copied without any warning. 5.2.15 Move File (movefile) movefile moves a file from one directory to another directory. The path of directory may be relative or absolute. Syntax is ✞ >>> [status , msg , msgid] = 2 >>> movefile (<source file >, <dest file >) ✌ ✆ ‘status’ handle returns the status of the operation, ‘msg’ returns message and ‘msgid’ is the id of the last message shown by Octave. 5.2.16 Rename a File (rename) rename renames a file name with another file name. Syntax is ✞ >>> [err , msg] = rename (<old name >, <new name >) ✌ ✆ It shows error if there is any error arises during this process & message if any returned by the Octave. 5.2.17 Delete a File (unlink) unlink deletes a file. Syntax is ✞ 1 >>> [err , msg] = unlink(<file name >) ✌ ✆ It shows error if there is any error arises during this process & message if any returned by the Octave. 5.3 I/O Operation Reading, writing and managing of a file is known as file operation. Input and output operations are reading and writing of a file. The functions which are used in file reading and writing are explained below. 5.3.1 End of File (feof) Returns ‘1’ if an end-of-file condition has been encountered for a given file and ‘0’ otherwise. It will only return ‘1’ if the end of the file has already been encountered otherwise next read operation will result in an end-of-file condition.
  • 35. 5.3. I/O OPERATION 185 https://sites.google.com/view/arunumrao ✞ 1 >>> f = fopen ("myfile.txt", "r"); >>> while (! feof (f) ) 3 >>> fgetl (f) # Read line by line >>> endwhile 5 >>> fclose (f); ✌ ✆ It will print file contents line by line of the file. 5.3.2 Clear a File Stream (fclear) It clears the stream state for the specified file. ✞ 1 >>> f = fopen ("myfile.txt", "r"); >>> fclear(f); 3 >>> fclose (f); ✌ ✆ 5.3.3 Open/Create a File (fopen) fopen command is used to open a file either in read or in write or in append mode. fopen command is used like ✞ 1 >>> f = fopen ("newfile.txt", "w"); ✌ ✆ It creates a file in the current working directory of Octave. Each and every file opened must be closed by using fclose command. It returns ‘-1’ if there is any error in the opening of a file otherwise it returns stream id. If multiple files are required to be opened, each opened file stream should be given a unique stream id by using hte sytax like ✞ 1 >>> f1 = fopen ("a.txt", "r"); >>> f2 = fopen ("b.txt", "r"); ✌ ✆ 5.3.4 Close a File (fclose) fclose closes the previously opened file. The file closing operation is performed like ✞ >>> f = fopen ("newfile.txt", "w"); 2 >>> fclose(f); ✌ ✆ If there are multiple file streams opened by function fopen by using same stream id then fclose closes only last open file until stream id is not provided as argu- ment. Octave gives error if there is any problem in closing of a opened file.
  • 36. 186 File Operation 5.3.5 Print Output (sprintf) It is similar to the printf except that it returns output as string. It automatically reallocated the memory size to be fit for storing whole data. Syntax used for this function is ✞ >>> sprintf (<conversion template >, <data >); ✌ ✆ 5.3.6 Output at Console (fprintf) This function is used like ✞ 1 >>> fprintf (<file_id >, <conversion template >, <data >); ✌ ✆ It is similar to the printf function except that, the data is stored in stream ‘file id’ rather that putting it into stdout. If stream file id is not assigned, it is displayed in stdout. 5.3.7 File Error (ferror) ferror returns ‘1’ if an error has been encountered for the file ID and it returns ‘0’ otherwise. ✞ 1 >>> f = fopen ("newfile .txt", "w"); >>> ferror(f); 3 >>> fclose(f); ✌ ✆ 5.3.8 File Report (freport) freport() returns the all old files whose are opened recently and the mode of their opening. ✞ 1 >>> freport () ✌ ✆ It returns the all file list with access mode. 5.3.9 Delete a File (delete) delete removes file from the disk. The path name of a file may be relative or absolute. ✞ 1 >>> delete("newfile.txt"); ✌ ✆ It shall remove the file “newfile.txt” from the disk.
  • 37. 5.3. I/O OPERATION 187 https://sites.google.com/view/arunumrao 5.3.10 Scan a Value (scanf) scanf scans input stream according to the template string. The syntax is ✞ 1 >>> [val , count] = scanf (<template >, <size >) ✌ ✆ It returns the scanned value and number of bytes scanned in vector form. 5.3.11 Formatted Scanning (sscanf) sscanf reads string in format based on template and copies it into output stream. The syntax is ✞ 1 >>> [val , count , errmsg , pos] = >>> sscanf (<input >, <template >, <variable >) ✌ ✆ It returns ‘true’ value if fscanf reads data successfully. 5.3.12 Rewind a Pointer (frewind) frewind sets the file pointer to the beginning of the file, returning 0 for success, and ‘-1’ if an error is encountered. ✞ >>> f=fopen(" myfile.txt","r"); 2 >>> ipos = ftell(f) # Show the current position >>> fgets(f,4); # Read the file four bytes 4 >>> ## Set the current position to four bytes from >>> ## from begining of file . 6 >>> fseek(f,4, SEEK_SET ); >>> cpos = ftell(f) # Get the current file pointer. 8 >>> frewind(f) # Set pointer at the beginning of file . >>> fpos = ftell(f) # Get the current position of file pointer. 10 >>> fclose(f); # Close the file . ✌ ✆ The output is ✞ ipos = = 0 cpos = = 4 fpos = = 0 ✌ ✆ 5.3.13 Scan to Buffer (fscanf) fscanf reads data from file stream and copies it into buffer stream. The syntax is
  • 38. 188 File Operation ✞ 1 >>> [val , count , errmsg] = >>> fscanf (<in file id >, <template >, <variable >) ✌ ✆ It returns ‘true’ value if fscanf reads data successfully. 5.3.14 Get Pointer Position (fseek) A pointer is positioned at offset pointer from the beginning of a file during the read mode of the file. Offset may be one of the predefined variables SEEK CUR (current position), SEEK SET (beginning), or SEEK END (end of file) or strings “cof”, “bof” or “eof”. If origin is omitted, SEEK SET is assumed by default. Offset may be positive, negative, or zero but not all combinations of origin and offset can be realized. ✞ >>> f=fopen("myfile.txt","r"); 2 >>> ipos = ftell(f) # Show the current position >>> fgets(f,4); # Read the file four bytes 4 >>> ## Set the current position after >>> ## four bytes from begining of a file . 6 >>> fseek(f, 4, SEEK_SET ); >>> fpos = ftell(f) # Get the current position of file . 8 >>> fclose(f); # Close the file . ✌ ✆ The output is ✞ ipos = 0 fpos = 4 ✌ ✆ 5.3.15 Pointer Position (ftell) ftell returns the current position of file pointer from the beginning of file. The position of file pointer is updated when a file is either read or wrote. fseek also updates the current position of file pointer. ✞ >>> f=fopen("myfile.txt","r"); 2 >>> ftell(f) >>> fclose(f); ✌ ✆ The output is ✞ ans = 0 ✌ ✆ 5.4 Reading Files Here we will discuss the function those are used in reading files.
  • 39. 5.4. READING FILES 189 https://sites.google.com/view/arunumrao 5.4.1 Read File by Lines (fgetl) fgetl is used to read characters from a file line by line. If length of characters is given, then these amount of characters are read. If length of characters is omitted then file is read until newline or EOF is not encountered. ✞ 1 >>> f = fopen ("myfile.txt","r"); >>> dt = fgetl (f,3) 3 >>> fclose (f); ✌ ✆ It reads only three chars of a line. In following example, Octave will read a whole line. ✞ 1 >>> f = fopen ("myfile.txt","r"); >>> dt = fgetl (f) 3 >>> fclose (f); ✌ ✆ It reads whole line. 5.4.2 Read File by Characters (fgets) It is similar to the fgetl. fgets is used to read characters from a file. If length of characters is given, then these amount of characters are read. If length of characters is omitted then file is read until newline or EOF is not encountered. ✞ 1 >>> f = fopen ("myfile.txt","r"); >>> dt = fgets (f,3) # Number of chars are 3 3 >>> fclose (f); ✌ ✆ It reads only three chars of a line. ✞ 1 >>> f = fopen ("myfile.txt","r"); >>> dt = fgets (f) # Read whole line 3 >>> fclose (f); ✌ ✆ It reads whole line. 5.4.3 Skip a Line (fskipl) It reads and skips the number of lines as specified in the second argument of the function. First argument to this function must be a file stream. ✞ 1 >>> f = fopen ("myfile.txt","r"); >>> dt = fskipl (f,3) # skips 3 lines 3 >>> fclose (f); ✌ ✆ If number of lines is not supplied, it skips only one line.
  • 40. 190 File Operation ✞ 1 >>> f = fopen ("myfile.txt","r"); >>> dt = fskipl (f) # skips only one line 3 >>> fclose (f); ✌ ✆ If number of line is ‘Inf’ then all the lines will be skipped until EOF is not encountered. ✞ 1 >>> f = fopen ("myfile.txt","r"); >>> dt = fskipl (f,Inf) # skips infinite lines 3 >>> fclose (f); ✌ ✆ 5.4.4 Read File in Binary (fread) fread is used to read a file in binary format. The syntax of this function is ✞ 1 >>> count = fread( >>> <file_id >, 3 >>> <buffer_size >, >>> <precision >, 5 >>> <skip >, >>> <architecture > 7 >>> ) ✌ ✆ Here, ‘file id’ is id of previously opened file. Argument ‘buffer size’ tells that how many binary data is to be read from stream file. The optional ‘buffer size’ values are given in the following table. Buffer Size Description Integer It is for specific number of data bytes. Inf Read data as much as possible. [r, Inf] Read data as much as possible, return- ing a matrix with ‘r’ rows. If the number of elements read is not an ex- act multiple of ‘r’, the last column is padded with zeros. [r, c] Read data by r × c elements, returning a matrix with ‘r’ rows. If the number of elements read is not an exact multiple of ‘r’, the last column is padded with zeros.
  • 41. 5.4. READING FILES 191 https://sites.google.com/view/arunumrao fread reads data equal to amount of ‘buffer size’ only and after that fread process terminated. The optional argument ‘precision’ defines the size of ele- ments to be read as one entity. The possible options are Options Description char Single character schar Single signed character uchar Single unsigned character int Integer uint Unsigned integer int8 8-bit signed integer int16 16-bit signed integer int32 32-bit signed integer int64 64-bit signed integer uint8 8-bit unsigned integer uint16 16-bit unsigned integer uint32 32-bit unsigned integer uint64 64-bit unsigned integer single 32-bit floating point number double 64-bit floating point number long Long integer ulong Unsigned long integer float Single precision floating point number The precision relation can be used as converter like ✞ 1 >>> int16=>int32 ✌ ✆ This causes fread to read 16-bit integer values and return an array of 32-bit integer values. The optional argument ‘skip’ specifies the number of bytes to skip after each element (or the block of elements) is read. If it is not specified, a value of 0 is assumed. If the final block read is not complete, the final skip is omitted. The argument ‘architecture’ defines the data format. The optional data formats are
  • 42. 192 File Operation Data Format Description native Data format of current machine ieee-be IEEE big endian ieee-le IEEE little endian vaxd VAX D floating format vaxg VAX G floating format cray Cray floating format The simple example of reading a file is by specific number of bytes. ✞ 1 >>> f = fopen ("myfile.txt","r"); >>> ## + Read only one byte 3 >>> ## | + One char data at once >>> dt = fread(f,1,"char ") # skips zero byte 5 >>> printf("%c",dt); >>> fclose (f); ✌ ✆ This will return the first byte as single character from the file that is open to read. Read two bytes data with one ‘char’ size at once. ✞ >>> f = fopen ("myfile.txt","r"); 2 >>> ## + Read only two bytes >>> ## | + One char data at once 4 >>> dt = fread(f,2,"char "); # skips zero byte >>> printf("%c",dt); 6 >>> fclose (f); ✌ ✆ An example of reading a file is by specific number of bytes with ‘skip’1 optional argument. ✞ >>> f = fopen ("myfile.txt","r"); 2 >>> ## + Read only 5 bytes data >>> ## | + One char data to be read at once 4 >>> dt = fread(f,5,"char " ,1) # skips one "char " after >>> # reading one "char " 6 >>> printf("%c", dt); >>> fclose (f); ✌ ✆ 1 If ‘precision’ is ‘char’ (say, it may be int or float as the case may be. It should be consider as basic unit of data.) then one ‘char’ size data is read at once. If ‘precision’ is supplied as ‘2*char’ then ‘two char’ size data is read at once. ‘buffer size’ should be sufficiently large to store the ‘precision’ size data. After each reading of group of ‘char’ elements, ‘skip’ times ‘char’ size data is skipped and again the ‘precision’ size data is read. fread reads until ‘buffer size’ is not filled by ‘precision’ data.
  • 43. 5.4. READING FILES 193 https://sites.google.com/view/arunumrao To read whole file of large size, use while loop environment with smaller buffer size. An example, with write and read functions, is given below ✞ 1 >>> f = fopen ("myfile.txt","w"); >>> fwrite(f,"This is myfile."); 3 >>> fclose (f); >>> f = fopen ("myfile.txt","r"); 5 >>> while( !feof (f) ) >>> dt=fread (f,1,"char " ,1,"ieee -be") 7 >>> printf("%c",dt); >>> endwhile 9 >>> fclose (f); ✌ ✆ read function reads one character byte and skips next character byte. The actual string (“This is my file.”) will appeared like ✞ Ti sm ie ✌ ✆ Another example with element of two char size and one char size of skip value is given below. ✞ 1 >>> f = fopen ("myfile.txt","w"); >>> fwrite(f,"This is myfile."); 3 >>> fclose (f); >>> f = fopen ("myfile.txt","r"); 5 >>> while( !feof (f) ) >>> dt=fread (f,10,"2* char " ,1,"ieee -be"); 7 >>> printf("%c",dt); >>> endwhile 9 >>> fclose (f); ✌ ✆ The output is ✞ Ths s y il. ✌ ✆ 5.4.5 CSV File Read (csvread) Function csvread() is used to read comma separated value file. Syntax for this function is ✞ 1 >>> csvread(<file name >); ✌ ✆ It read entire cvs file. To read specific range of data, dlmread() (delimiter read) funciton is used. ✞ 1 >>> dlmread(<file name >, <separator >, <from row >, <from column >) ✌ ✆
  • 44. 194 File Operation To read ‘csv2.txt’, function is used as ✞ 1 >>> csvread (’csv2 .txt’) ✌ ✆ ✞ ans = 0 0 0 0 0 0 0 0 0 3 6 9 12 15 0 0 5 10 15 20 25 0 0 7 14 21 28 35 0 0 11 22 33 44 55 ✌ ✆ ✞ >>> dlmread (’csv2 .txt’,’,’ ,2,2) ✌ ✆ ✞ ans = 5 10 15 20 25 7 14 21 28 35 11 22 33 44 55 ✌ ✆ 5.5 Writing Files Writing contents into a file is performed by following methods. 5.5.1 Write Into File Unformatted (fputs) fputs write a string to a file without formatting at the end of file. In other words, it appends data into a file. ✞ >>> f = fopen ("myfile.txt","w"); 2 >>> dt = fputs (f,"This is my file .") >>> fclose (f); ✌ ✆ On successful writing into a file, fputs returns ‘true’ value. 5.5.2 Write Into a File (fwrite) fwrite puts contents on a file opened previously by fopen function. The syntax of this function is ✞ 1 >>> count = fwrite ( >>> <file_id >, 3 >>> <data >, >>> <precision >, 5 >>> <skip >, >>> <arch > 7 >>> ) ✌ ✆
  • 45. 5.5. WRITING FILES 195 https://sites.google.com/view/arunumrao Here, argument ‘file id’ is the id of previously opened file into which ‘data’ is to be written. ‘data’ is in binary format. The remaining arguments ‘precision’, ‘skip’, and ‘arch’ are optional. ‘count’ returns the number of bytes written successfully into the file. The optional argument ‘precision’ defined the size of elements to write as one entity. The possible options are Options Description char Single character schar Single signed character uchar Single unsigned character int Integer uint Unsigned integer int8 8-bit signed integer int16 16-bit signed integer int32 32-bit signed integer int64 64-bit signed integer uint8 8-bit unsigned integer uint16 16-bit unsigned integer uint32 32-bit unsigned integer uint64 64-bit unsigned integer single 32-bit floating point number double 64-bit floating point number long Long integer ulong Unsigned long integer float Single precision floating point number The precision relation can be used as converter like ✞ 1 int16=>int32 ✌ ✆ This causes fwrite to write 16-bit integer values and return an array of 32-bit integer values. The optional argument ‘skip’ specifies the number of bytes to skip after each element (or block of elements) is write. If it is not specified, a value of 0 is assumed. If the final block write is not complete, the final skip is omitted. The argument ‘architecture’ defines the data format. The optional data formats are
  • 46. 196 File Operation Data Format Description native Data format of current machine ieee-be IEEE big endian ieee-le IEEE little endian vaxd VAX D floating format vaxg VAX G floating format cray Cray floating format A working example is ✞ 1 >>> f = fopen ("myfile.txt","w"); >>> dt = fwrite (f,"This is my file .") # skips zero byte 3 >>> fclose (f); ✌ ✆ ✞ This is my file ✌ ✆ Use of fwrite with optional argument ‘precision’ is ✞ 1 >>> f = fopen ("myfile.txt","w"); >>> dt = fwrite (f,"This is my file .","char ") # skips zero byte 3 >>> fclose (f); ✌ ✆ ✞ This is my file ✌ ✆ Use of fwrite with optional argument ‘precision’ and ‘skip’ is ✞ 1 >>> f = fopen ("myfile.txt","w"); >>> dt = fwrite (f,"This is my file .","char " ,1) # skips one byte 3 >>> fclose (f); ✌ ✆ When we open the text file in which data is written we find that after each char of the string, there is a null skipped character (one null byte)2 . ✞ T h i s i s m y f i l e . ✌ ✆ An finally use of ‘architecture’ of the data type. 2 Space appears, when file is opened in notepad and unknown blocks are appeared in word- pad.
  • 47. 5.5. WRITING FILES 197 https://sites.google.com/view/arunumrao ✞ 1 >>> f = fopen ("myfile.txt","w"); >>> dt = fwrite (f,"This is my file .","char " ,1,"ieee -be") 3 >>> fclose (f); ✌ ✆ ✞ T h i s i s m y f i l e . ✌ ✆ 5.5.3 CSV Write (csvwrite) CSV stands for Comma Separated Value. csv write data into comma separated value file. Each data row is terminated by semi-colon ‘;’. Data in each row separated by space. Data should be in matrix form. Its syntax is ✞ 1 >>> csvwrite (<file name >, <data handle >); ✌ ✆ ✞ 1 >>> m = [3 6 9 12 15; 5 10 15 20 25; >>> 7 14 21 28 35; 11 22 33 44 55]; 3 >>> csvwrite (’csv1 .txt’,m) ✌ ✆ With column offsets the same function is used as ✞ 1 >>> csvwrite (<file name >, >>> <data handle >, 3 >>> <number of offset rows >, >>> <number of offset cols > 5 >>> ); ✌ ✆ ✞ 1 >>> m = [3 6 9 12 15; 5 10 15 20 25; >>> 7 14 21 28 35; 11 22 33 44 55]; 3 >>> csvwrite (’csv2 .txt’,m,1,2) ✌ ✆ To formatted write, CSV files are written with dlmwrite() function. ✞ 1 >>> dlmwrite ( >>> <file name >, 3 >>> <data >, >>> <row offset >, 5 >>> <col offset >, >>> <key name >, 7 >>> <key value >, >>> <options > 9 >>> ) ✌ ✆ 1. append : It is used to select append mode on or off.
  • 48. 198 File Operation 2. delimiter : This key is used to controll the delimiter type. A delimiter may be any alpha-numeric character or special symbol. 3. newline : The character(s) to use to separate each row. Three special cases exist for this option. “unix” is changed into “n”, “pc” is changed into “rn”, and “mac” is changed into “r”. Any other value is used directly as the newline separator. 4. precision : It controls the significant digits. ✞ 1 >>> m = [3 6 9 12 15; 5 10 15 20 25; >>> 7 14 21 28 35; 11 22 33 44 55]; 3 >>> dlmwrite ("dsv.tex", m, "delimiter ", "&", "newline ", "n"); ✌ ✆ 5.6 GUI Building 5.6.1 Getting Directory The directory listing or choosing dialog is opened by uigetdir() function. Syn- opsis of this function is used one of the listed below. ✞ 1 >>> dirname = uigetdir () >>> dirname = uigetdir (<initial path >) 3 >>> dirname = uigetdir (<initial path >, <dialog name >) ✌ ✆ In example below, a dialog is opened indicating to initial path to ‘/’. After selection of a directory and choosing it, the function returns directory name to function handler ‘dirname’. The directory name is displayed in output by disp() function. ✞ 1 >>> dirname = uigetdir ("/","Select Directory "); >>> disp ( dirname); ✌ ✆ ✞ /mnt ✌ ✆ 5.6.2 Getting a File A filtered file selection can be performed by uigetfile() function by using full discription as shown below. ✞ 1 >>> [filename , filepath , fileindex ] = >>> uigetfile ( 3 >>> <filtered extension >,
  • 49. 5.6. GUI BUILDING 199 https://sites.google.com/view/arunumrao >>> <dialog name >, 5 >>> <default file >, >>> "Position ", 7 >>> [px py], >>> "MultiSelect ", 9 >>> <mode > >>> ) ✌ ✆ We can omit one or all of the inputs but “position” & [px py] and “MultiSelect” & mode shall be omitted in pair. Selected file name is returned to ‘filename’, file path is returned to ‘filepath’. Each file in multimode selection is assigned a unique id to ‘fileindex’. ✞ >>> [filename , filepath , fileindex ] = uigetfile () ✌ ✆ ✞ filename = b.m filepath = /home /arun / fileindex = 1 ✌ ✆ 5.6.3 Process Status Durint the process, process progress can be visualized by wait bar. Wait bar in Octave is activated by waitbar() function. Its synopsis is ✞ 1 >>> <hid >= waitbar ( >>> <fract [0, 1]>, 3 >>> <message >, >>> <figure property 1>, 5 >>> <property 1 value >, >>> <figure property 2>, 7 >>> <property 2 value >, >>> ................. 9 >>> ................. >>> ) ✌ ✆ In this function, fraction value may be in range of [0, 1]. ‘message’ is the description about the wait bar. Properties and their corresponding values are used simultaneously. ✞ >>> <handle id >= waitbar (0.4,"% completed "); ✌ ✆ Above method is used to open a waiting bar GUI and creation of its handle id. To update a waiting bar with new fraction value, waitbar() function is used again as given in following syntax. ✞ 1 >>> waitbar(<fraction >, <handle id >, <message >); ✌ ✆
  • 50. 200 File Operation New fraction value shall be updated to the waiting bar identified by ‘handle id’. ✞ 1 >>> h=waitbar (0,"% completed "); >>> for(x =0:0.01:1) 3 >>> waitbar (x,h,"% completed "); >>> endfor ✌ ✆ 5.6.4 Creating a Panel uipanel() creates a panel for arranging of controls. Its syntax is ✞ >>> <hid > = uipanel ( 2 >>> "parent", >>> <parent figure handler >, 4 >>> <property 1>, >>> <value for property 1>, 6 >>> .............. >>> ) ✌ ✆ If ‘parent’ (value “parent”) is omitted then a uipanel for the current figure is created. If no figure is available, a new figure is created first. ✞ 1 >>> f = figure; >>> p = uipanel ( 3 >>> "title", #property title >>> "Graphics Panel", #value for property title 5 >>> "position ", #property position >>> [.25 .25 .5 .5] #value for property position 7 >>> ); >>> b1 = uicontrol ( 9 >>> "parent", #parent window >>> p, #figure handle 11 >>> "string", #control property string >>> "A Button", #string value 13 >>> "position ", #position property >>> [10 10 150 40] #position value 15 >>> ); >>> e1 = uicontrol ( 17 >>> "parent", #parent window >>> p, #figure handle 19 >>> "style", #control style >>> "edit ", #control type edit 21 >>> "string", #control property string >>> "An edit box", #string value 23 >>> "position ", #position property >>> [10 50 150 40] #position value 25 >>> ); >>> c1 = uicontrol (
  • 51. 5.6. GUI BUILDING 201 https://sites.google.com/view/arunumrao 27 >>> "parent", #parent window >>> p, #figure handle 29 >>> "style", #control style >>> "checkbox ", #control type edit 31 >>> "string", #control property string >>> "A check box", #string value 33 >>> "position ", #position property >>> [10 100 150 40] #position value 35 >>> ); ✌ ✆ 5.6.5 User Interactive Menu The function uimenu is used to create user interactive menus. Its syntax is like ✞ 1 >>> u = uimenu(h, <property >, <value >, ....) ✌ ✆ If ‘h’ is omitted then a top-level menu for the current figure is created. If ‘h’ is given then a submenu relative to ‘h’ is created. A top level menu should have atleast one sub menu. The properties used with this function are “accelerator” whose value is a string that is used as shortcut key with CTRL key. “callback” property tells about the named function that will be executed if the correspond- ing menu is interacted. The callback function may be either string name or an object name, i.e. function name prefixed with‘@’ symbol without double quotes. The callback function may be a cell array with function object name and its arguments like {@f, arg1, arg2}. “foregroundcolor” for text colours. “label” for menu label. The label value may have a ‘&’ symbol that can be marked as accelerator. “position” for relative menu position.The entry with the lowest value is at the first position starting from left or top. “separator” key has ”on” or ”off” value. If enabled it draws a separator line above the current position. It is ignored for top level entries. ✞ 1 >>> f = figure; >>> ## create top level menu in the context menu 3 >>> m1 = uimenu (f,"label","Add"); >>> ## Create sub menu under Add top level menu 5 >>> uimenu (m1 ,"label","Display Add","callback ","disp (’Add ’)"); >>> ## create top level menu in the context menu 7 >>> m2 = uimenu (f,"label","Save "); >>> ## Create sub menu under Add top level menu 9 >>> uimenu (m2 ,"label","Display Save ","callback ","disp (’Save ’)"); ✌ ✆
  • 52. 202 File Operation 5.6.6 Create a Context Menu Context menus are those menus which are appear on the right click over the fig- ure where context menu is created. This menu does not appear either in toolbar or in window. The construction of context menu is similar to the construction of user interactive menus. The syntax of this function as given below. ✞ 1 >>> <HUI > = uicontextmenu ( >>> <handle id >, 3 >>> <property 1>, >>> <value of property 1>, 5 >>> <property 2>, >>> <value of property 2>, 7 >>> .......... >>> ) ✌ ✆ If ‘handle id’ is omitted, any change provided shall be applicable to the current figure. ✞ >>> f = figure; 2 >>> c = uicontextmenu (f); >>> % create menus in the context menu 4 >>> m1=uimenu("parent",c," label","Add"," callback ","disp (’Add ’)"); >>> m2=uimenu("parent",c," label","Save ","callback ","disp (’Save ’)"); 6 >>> % set the context menu for the figure >>> set (f, "uicontextmenu ", c); ✌ ✆ 5.6.7 Put String with Mouse The function gtext places text on the current figure using the mouse. The string passed to this function may be single cell value or cell array. A cell array string is placed with every mouse click. ✞ 1 >>> f = figure; >>> function AddText(h, e, t) 3 >>> txt = inputdlg ("Enter string"); >>> h=gtext(txt); 5 >>> endfunction >>> c = uicontextmenu (f); 7 >>> ## create menus in the context menu >>> m1=uimenu("parent",c, 9 >>> "label","Add Text ", >>> "callback " ,{@AddText ,f}); 11 >>> set (f, "uicontextmenu ", c); ✌ ✆
  • 53. 5.6. GUI BUILDING 203 https://sites.google.com/view/arunumrao In Octave, we can listen mouse click and its location over figure by using ginput function. It is used over graphics. We can use text function to put arbitrary string at given location over plots. This function is used as shown below: ✞ 1 >>> [x, y, btn] = ginput(<figure id >) ✌ ✆ Here, x, y are coordinate values and btn is button pressed. btn value is 1 for left click, 2 for middle mouse button press, 3 for right click and ascii code of any other button pressed. It applications are given below: ✞ 1 >>> f = figure; >>> function AddText(h, e, t) 3 >>> txt = inputdlg ("Enter string"); >>> [x,y,b]= ginput(t); 5 >>> text (x, y, txt); >>> endfunction 7 >>> c = uicontextmenu (f); >>> ## create menus in the context menu 9 >>> m1=uimenu("parent",c, >>> "label","Add Text ", 11 >>> "callback " ,{@AddText ,f}); >>> set (f, " uicontextmenu ", c); ✌ ✆ 5.6.8 Create Control uicontrol() creates a control object and object id is returned as handler to it. It is used to created simple interactive controls such as push button, check-boxes, edit and list controls. If ‘parent’ is omitted then a uicontrol() is created for current figure. If there is no figure then a new figure is created first. There are following types of controls: 1. checkbox : It creates check box for on/off control. 2. edit : Creates editable text box for user input. 3. listbox : Creates a selectable list box like drop-down button. 4. popupmenu : Creates a pop up menu control which displays a list of options for user selection. 5. pushbutton : Create a push button. Action related to push button is performed by clicking on the button. 6. radiobutton : Create a radio button control intended to use exclusive input in a group of radio button control. 7. slider : Creates a slider control that allows user to select an input value by the relative position of the knob of the slider.
  • 54. 204 File Operation 8. text : Creates a static text control. 9. togglebutton : Creates a toggle button control that appears like a push button. But it allows to select only one state. These controls are invoked by style, i.e. these are values of style property. Syntax for the function is ✞ >>> <hid > = uicontrol ( 2 >>> <figure handle id >, >>> <property 1>, 4 >>> <value for property 1>, >>> .............. 6 >>> ) ✌ ✆ In the following lines of code, three user interactive controls are added into the graphics pane. ✞ >>> f = figure; 2 >>> b1 = uicontrol (f, #figure handle >>> "string", #control property string 4 >>> "A Button", #string value >>> "position ", #position property 6 >>> [10 10 150 40] #position value >>> ); 8 >>> e1 = uicontrol (f, #figure handle >>> "style", #control style 10 >>> "edit ", #control type edit >>> "string", #control property string 12 >>> "An edit box", #string value >>> "position ", #position property 14 >>> [10 50 150 40] #position value >>> ); 16 >>> c1 = uicontrol (f, #figure handle >>> "style", #control style 18 >>> "checkbox ", #control type edit >>> "string", #control property string 20 >>> "A check box", #string value >>> "position ", #position property 22 >>> [10 100 150 40] #position value >>> ); ✌ ✆ In the following figure, we have creates a slider and text control in the figure window. The slider uses callback named function ‘cb’ to update the text control string with the current value of slider. The controls first search callback function in built-in function list, then in the same code script and finally the working directory. If callback function is in same code script file, then prefer that it is before the calling controls. In the following example, the callback function is in the same code script.
  • 55. 5.6. GUI BUILDING 205 https://sites.google.com/view/arunumrao ✞ 1 >>> function cb( ) >>> ## Copy the graphics data to handle g 3 >>> g = guidata (gcf); >>> ## Get the slider value 5 >>> sv = get(g.s,’value’); >>> ## Set the text value to slider value 7 >>> set(g.t,’string’,num2str (sv , "%10.5f")); >>> endfunction 9 >>> ## Create a figure and handler object f >>> f = figure(’position ’ ,[100 100 500 500],’units’,’pixels’); 11 >>> ## Retrieve the figure property structure of figure f. >>> ## We can use gcf() function too but it returns figure 13 >>> ## data of current figure not of targeted figure >>> h = get(f); 15 >>> ## Add a slider control . Add its handler to member s of h >>> h.s = uicontrol (’style’,’slider’,’position ’, 17 >>> [60 20 400 20], ’callback ’,@cb); >>> ## The above callback function does not supplied arguments 19 >>> ## >>> ## Add a text control. Add its handler to member t of h 21 >>> h.t = uicontrol (’style’,’text ’, >>> ’string ’, ’?????’, 23 >>> ’position ’ ,[60 50 400 20]) ; >>> ## Bind the data of handler h into f 25 >>> guidata(f,h); ✌ ✆ To allow the callback function with supplied arguments, the ‘callback’ key of user interactive control object must have value in cell value structure, in which first value is named or object callback function, and rest are arguments for the callback function. ✞ 1 >>> h.s = uicontrol (’style’,’slider’,’position ’, >>> [60 20 400 20], ’callback ’,{@cb , 0.5}); ✌ ✆ But the structure of callback function being executed has two default parameters and rest are argument parameters. The first parameter is source handle, i.e. the user interactive control that is calling to this function, second is event, i.e. left button click, middle button click, right button click, key press, button down or button up etc., and rest are augment parameters. The argument parameters may be other user interactive control handles, i.e. target control, too. ✞ >>> function cb(h, e, v) 2 >>> <function bod > >>> endfunction ✌ ✆
  • 56. 206 File Operation The complete example for callback function is modified as given below: ✞ 1 >>> function cb(h, e, v) >>> g = guidata(gcf); 3 >>> sv = get(g.s,’value’); >>> if(sv >v) 5 >>> set(g.t,’string ’,num2str(sv , "%10.5f")); >>> endif 7 >>> endfunction >>> f = figure(’position ’ ,[100 100 500 500],’units’,’pixels’); 9 >>> h = get(f); >>> h.s = uicontrol (’style’,’slider’,’position ’, 11 >>> [60 20 400 20], ’callback ’,{@cb , 0.5}); >>> h.t = uicontrol (’style’,’text ’, 13 >>> ’string ’, ’?????’, >>> ’position ’ ,[60 50 400 20]) ; 15 >>> guidata (f,h); ✌ ✆ We can also pass the target object handle via uicontrol callback to the callback function being executed. See the program given below: ✞ 1 >>> function update(hs , e, ht) >>> sv = get(hs ,’value’); 3 >>> set(ht ,’string’,num2str(sv , " %10.5f")); >>> endfunction 5 >>> f = figure(’position ’ ,[100 100 500 500], >>> ’units’,’pixels’); 7 >>> t1 = uicontrol (’style’,’text ’, >>> ’string ’, ’?????’, 9 >>> ’position ’ ,[350 20 100 20]) ; >>> s1 = uicontrol (’style’,’slider’,’position ’, 11 >>> [10 20 300 20], ’callback ’,{@update , t1}); >>> t2 = uicontrol (’style’,’text ’, 13 >>> ’string ’, ’?????’, >>> ’position ’ ,[350 50 100 20]) ; 15 >>> s2 = uicontrol (’style’,’slider’,’position ’, >>> [10 50 300 20], ’callback ’,{@update , t2}); ✌ ✆ Note that, the target handle that is being passed to callback function, must be created before the calling of callback function as shown in above figure. The basic callback functions that are available for all graphics objects. These are CreateFcn that is called at the moment of the objects creation. Callbacks that are added to CreateFcn later with the set function will never be executed. DeleteFcn is called at the moment an object is deleted. ButtonDownFcn is called if a mouse button is pressed while the pointer is over this object. There are hundreds of the kye-value properties related to the user interactive controls and toolbars. Each property can not be listed or explained here. We can get
  • 57. 5.6. GUI BUILDING 207 https://sites.google.com/view/arunumrao the list of all associated properties to specific uicontrol by using get function as shown below: ✞ >>> h = uicontrol (); 2 >>> get(h) ✌ ✆ ✞ ans = scalar structure containing the fields: beingdeleted = off busyaction = queue buttondownfcn = [](0 x0) children = [](0 x1) clipping = on ................. units = pixels value = 1 verticalalignment = middle ✌ ✆ Be careful while applying key-value properties. A uicontrol has own specific properties. Therefore before using a key-value property, first check it whether it is member of the control or not by using get function as explained above. Many properties has general meaning and purposes which are well known to the learners, like font, font size, font weight, font type, foreground colour, back- ground colour, color etc. For these properties the GNU-Octave help page can be referred. Here, only important key-value properties are explained.
  • 58. 208 File Operation Key Value & Description accelerator It is character used with CTRL function. It works in menu control. busyaction What to do when control is busy. buttondownfcn What to do when middle or right mouse button pressed. createfcn On action create function. deletefcn On action delete function. handlevisibility Visibility of handle. Default is on. interruptible Whether control is interruptible or not. Default is on. parent Graphics window level. selected Control is selected by default. visible Control is visible or not. callback What shall be returned on action. cdata Image data. enable Control is enabled or disabled. Default is on. max It controls the maximum value of the control. min It controls the minimum value of the control. sliderstep Number of steps in a slider. string Name of control. style Type of the control. tooltipstring Returns the string when hover on the control. units Measuring units of the graphical window and control tools. value Returned value of the control. Table 5.1: Description of properties most commonly used with uicontrol. Example of Tooltip String A tooltip string is flashes when mouse pointer is placed over the control tool. It is just like hint about the tool. See the example given below: ✞ 1 >>> h = uicontrol (’style’,’pushbutton ’, >>> ’tooltipstring ’,’Click it’, 3 >>> ’string ’,’OK’); ✌ ✆
  • 59. 5.6. GUI BUILDING 209 https://sites.google.com/view/arunumrao Button Down Function A buttondownfcn is executed when middle or right mouse button is pressed. Note that when left mouse button is pressed, then it is called click. ✞ 1 >>> h = uicontrol (’style’,’pushbutton ’, >>> ’tooltipstring ’,’Click it’, 3 >>> ’buttondownfcn ’,"disp (’Pressed ’)", >>> ’string’,’OK’); ✌ ✆ ✞ Pressed Pressed Pressed Pressed ✌ ✆ 5.6.9 Figure Tool uipushtool() creates a button that appear on a figure toolbar. The button is created with a border that is shown when the user hovers over the button. Image can set by using ‘cdata’ property. Syntax of this function is ✞ >>> <hui > = uipushtool ( 2 >>> "parent", >>> <property 1>, 4 >>> <value for property 1>, >>> ............. 6 >>> ); ✌ ✆ If “parent” is omitted then a user interactive push tool for the current figure is created. If no figure is available, a new figure is created first. If a figure is available, but does not contain a user interactive toolbar, a user interactive toolbar will be created. ✞ >>> f = figure ("toolbar", "none "); 2 >>> % Create empty toolbar >>> t = uitoolbar (f); 4 >>> % Create a 19 x19x3 black square >>> img=zeros (19 ,19 ,3); 6 >>> % Add pushtool button to toolbar >>> b = uipushtool (t, "cdata", img); ✌ ✆ 5.6.10 Toggle Tool uitoggletool() creates a button that appear on a figure toolbar. The button is created with a border that is shown when the user hovers over the button. Image can set by using ‘cdata’ property. Syntax of this function is
  • 60. 210 File Operation ✞ 1 >>> <hui > = uitoggletool ( >>> "parent", 3 >>> <property 1>, >>> <value for property 1>, 5 >>> ............. >>> ); ✌ ✆ If “parent” is omitted then a toggle button for the current figure is created. If no figure is available, a new figure is created first. If a figure is available, but does not contain a toggle button, a toggle button will be created. ✞ >>> f = figure ("toolbar ", "none "); 2 >>> % create empty toolbar >>> t = uitoolbar (f); 4 >>> % create a 19 x19x3 black square >>> img=zeros (19 ,19 ,3); 6 >>> % add uitoggletool button to toolbar >>> b = uitoggletool (t, "cdata", img); ✌ ✆ 5.6.11 Dialogue Box Dialogues are those pop-up windows which are used for specific purposes, like showing hints, showing errors, for users’ input etc. Followings are the different dialogues which are implemented in Octave. ✞ 1 >>> h = dialog (<property >, <value >, ...) ✌ ✆ Creates a transparent dialogue window in which different controls can be put by using uicontrol function. Error showing dialogue is created as shown below: ✞ 1 >>> errordlg (<Error n instructions >, <dialogue title >); ✌ ✆ The hint dialogue is shown below: ✞ 1 >>> h = helpdlg (msg , title) ✌ ✆ The input dialogue is define as shown below: ✞ 1 >>> pr = {"W", "H"}; // field labels >>> def = {"1", "2"}; // default values 3 >>> rc = [1 ,10; 2,20; 3 ,30];// rows and cols of the input field >>> dims = inputdlg (pr , "Enter Box Dimensions ", rc , def); ✌ ✆ Question dialogue is used with three option buttons. The return value is button name string.
  • 61. 5.6. GUI BUILDING 211 https://sites.google.com/view/arunumrao ✞ >>> btn = questdlg (msg , title , btn1 , btn2 , btn3 , default ); ✌ ✆ To highlight the dialogue’s default button, default value should be exactly the button name. Message dialogue is created as shown below: ✞ 1 >>> msgbox (msg , title , icon ); ✌ ✆ Warning dialog shows fancy warning. ✞ 1 >>> warndlg ({ line 1, line 2}, title); ✌ ✆ The listdlg, i.e. list dialogue shows a list of available options. On clicking over OK button after selection of the options, it returns the index of selected option. Index count in Octave is started from one to infinite. ✞ 1 >>> myO = {"A", "B", "C"}; >>> [sel , ok] = listdlg ("ListString ", myO , options); ✌ ✆ The first argument is compulsory. Options are provided in a group of key-value options. The main options are “SelectionMode” key has “Single” or “Multiple’ option values. “ListSize” is a vector which two elements in which first is width and second is height. Default initial values are provided with “InitialValue” key. “Name” shows the name of dialogue. “OKString” and “CancelString” are used for naming OK button and Cancel button respectively. “PromptString” key is used to define the label of field. In all above dialogues, first argument is message shown in dialogue body and second is dialogue title argument. Rest arguments are specific inputs of the respective dialogue. 5.6.12 Tool Bar uitoolbar() creates a user’s interactive toolbar and return a handle to it. A uitoolbar displays uitoggletool and uipushtool buttons. ✞ >>> <hui > = uitoolbar ( 2 >>> "parent", >>> <parent handler >, 4 >>> <property 1>, >>> <value for property 1>, 6 >>> ............. >>> ); ✌ ✆ If “parent” is omitted then a toolbar for the current figure is created. If no figure is available, a new figure is created first. If a figure is available and it does not contain a toolbar then a toolbar will be created. ✞ 1 >>> f = figure ("toolbar", "none "); >>> ## Create empty toolbar
  • 62. 212 File Operation 3 >>> t = uitoolbar (f); ✌ ✆ 5.6.13 Preferences getpref returns the preference value corresponding to the named preference in a group. setpref sets a preference to a given value in the named preference group. addpref adds a preference and associated value to the named preference group. rmpref remove the named preference from the preference group. ispref returns true if the named preference exists in the preference group. prefdir return the directory that contains the preferences for Octave. to change the preference directory cd() function is used. ✞ 1 >>> addpref (’mytoolbox ’,’version ’,’1.0 ’) >>> getpref (’mytoolbox ’,’version ’) 3 >>> setpref (’mytoolbox ’,’version ’,’1.1 ’) >>> getpref (’mytoolbox ’,’version ’) 5 >>> rmpref(’mytoolbox ’,’version ’) >>> getpref (’mytoolbox ’,’version ’,’1.2 ’); 7 >>> getpref (’mytoolbox ’,’version ’) ✌ ✆ ✞ ans = 1.0 ans = 1.1 error: preference version does not exist in group mytoolbox error: called from getpref at line ....... ✌ ✆ 5.6.14 GUI Data The function guidata() either used to get the current GUI data or used to update the GUI data. It accepts one argument during querying about data and two arguments during updating of figure data. First argument is figure handler and second argument is data. The syntax for querying GUI data, the function is used like ✞ >>> <data > = guidata(< figure handle >); ✌ ✆ To set the user defined data, guidata() is used like ✞ 1 >>> guidata (<figure handle >, <data >) ✌ ✆ The GUI data is stored in the figure handle ‘h’. If ‘h’ is not a figure handle then it’s parent figure will be used for storage. ‘data’ must be a single object which means it is usually preferable for it to be a data container such as a cell array or structure so that additional data items can be added easily. Before writing a demo program, we will discuss about the working procedure of guidata function.
  • 63. 5.6. GUI BUILDING 213 https://sites.google.com/view/arunumrao Let we have a figure that is created with figure function. The figure object is assigned to the handler ‘h’. ✞ 1 >>> f = figure () ✌ ✆ ✞ f = 1 ✌ ✆ We can assign our own key value data to figure object. To do this, we must have to first get the current graphic figure using get function. get function converts scalar handler into structure. ✞ 1 >>> f = figure (); >>> h = get(f) ✌ ✆ ✞ h = scalar structure containing the fields: beingdeleted = off busyaction = queue buttondownfcn = [](0 x0) children = [](0 x1) ................. xdisplay = xvisual = xvisualmode = auto ✌ ✆ The object fields or object members are created by using dot symbol as shown in the following code lines. The object members created by dot symbol does not appear in the figure until unless updated figure data is not copied into the figure handler by using guidata function. ✞ 1 >>> f = figure (); >>> h = get(f); 3 >>> h.xrange = 1:10; >>> h ✌ ✆ ✞ h = scalar structure containing the fields: beingdeleted = off busyaction = queue buttondownfcn = [](0 x0) children = [](0 x1) ................. wvisualmode = auto xdisplay = xvisual = xvisualmode = auto
  • 64. 214 File Operation xrange = 1 2 3 4 5 6 7 8 9 10 ✌ ✆ Note that, in the following code lines, which contains uicontrol functions, i.e. ✞ 1 >>> f = figure (); >>> h = get(f); 3 >>> h.a=uicontrol () >>> b = uicontrol (f) 5 >>> h >>> f ✌ ✆ have same effect in figure output. But, first control object ‘a’ is in same hierarchy level as the object ‘h’ is and second control object ‘b’ is children of the parent figure ‘f’. ✞ a = -2.8959 b = -4.8228 h = scalar structure containing the fields: beingdeleted = off busyaction = queue buttondownfcn = [](0 x0) children = [](0 x0) ........... xvisual = xvisualmode = auto a = -2.8959 f = scalar structure containing the fields: beingdeleted = off busyaction = queue buttondownfcn = [](0 x0) children = -4.8228 -3.5636 -1.3503 -2.8959 ........... xvisual = xvisualmode = auto ✌ ✆ Now a question is here, that what happens if we add axes into the figure as its member value without calling get or gcf function. The answer is that, the figure function returns the figure object id to its handler and it is a scalar value. So, that structure (key-value arrangement) can not be added to it. ✞ 1 >>> f = figure (); >>> f.a=axes ()
  • 65. 5.6. GUI BUILDING 215 https://sites.google.com/view/arunumrao 3 >>> get(f) ✌ ✆ ✞ error: scalar cannot be indexed with . error: assignment failed , or no method for ’scalar = scalar ’ f = scalar structure containing the fields: beingdeleted = off busyaction = queue buttondownfcn = [](0 x0) children = [](0 x1) ................. xvisual = xvisualmode = auto ✌ ✆ But if we add axes to current figure then Octave adds it as children of the parent figure window. ✞ 1 >>> f = figure (); >>> a = axes () 3 >>> get(f) ✌ ✆ ✞ h = scalar structure containing the fields: beingdeleted = off busyaction = queue buttondownfcn = [](0 x0) children = -39.534 ................. xvisual = xvisualmode = auto ✌ ✆ Now, to access the axes properties, we have to use axes handler as shown in the following codes: ✞ 1 >>> f = figure (); >>> a = axes () 3 >>> get(a) ✌ ✆ ✞ ans = scalar structure containing the fields: beingdeleted = off busyaction = queue buttondownfcn = [](0 x0) children = [](0 x1) ................. zticklabel = {
  • 66. 216 File Operation [1,1] = 0 [1,2] = 0.2 [1,3] = 0.4 [1,4] = 0.6 [1,5] = 0.8 [1,6] = 1 } zticklabelmode = auto ztickmode = auto ✌ ✆ The function guidata adds the current data of figure into the handler of the figure. Following is an demo example that is using the GUI controls andguidata. guidata is used to clean the figure for new plot. In my file ‘demo.m’ following codes are written. ✞ >>> ## Create a figure with handler object f 2 >>> f = figure(’position ’ ,[100 100 500 500],’units’,’pixels’); >>> ## Get the graphics structure of figure f 4 >>> h = get(f); >>> ## Add axes data to member a of handler h 6 >>> h.a = axes (’units’,’pixels’,’position ’ ,[60 ,100 ,400 ,300]) ; >>> ## Add a slider control . Add its value to member s of h 8 >>> h.s = uicontrol (’style’,’slider’,’position ’, >>> [60 20 400 20], ’callback ’,@cb); 10 >>> ## Create x value member into the handler h >>> h.xrange = 1:100; 12 >>> ## Bind the window id to member f of handler h >>> guidata (f,h); ✌ ✆ The callback function is defined in file ‘cb.m’. ✞ 1 >>> function cb( ) >>> ## Clean the figure 3 >>> g = guidata(gcf); >>> ## Get the slider value 5 >>> sv = get(g.s,’value’); >>> ## Plot the new function with new slider value 7 >>> ## and copy it into the axes object , i.e. >>> ## its parent window is g.a 9 >>> plot (g.xrange , sv*sin(g.xrange),’parent’,g.a); >>> endfunction ✌ ✆ Both files are saved in same path and ‘demo.m’ is run from octave. On run of GUI, we can redraw, plot for different slider value. Remember that the callback function name and callback function file name, both must be same.
  • 67. 5.6. GUI BUILDING 217 https://sites.google.com/view/arunumrao 5.6.15 Handler GUI The function guihandles() return a structure of object handles for the figure associated with handle. Syntax of this function is ✞ >>> <hdata > = guihandles (< figure handle >) ✌ ✆ 5.6.16 Wait For Time The function uiwait suspend program execution until the figure with handle supplied handle is deleted or uiresume is not called. If there is no handle supplied to this function, current figure is used by default. In case of invalid figure handle or there is not current figure, this function returns immediately. The minimum timeout value is 1. If timeout value is not specified, the program execution is suspended indefinitely. ✞ 1 >>> f = figure; >>> function AddText(h, e, t) 3 >>> uiwait(t, 5); ## wait for 5 seconds >>> txt = inputdlg ("Enter string"); 5 >>> [x,y,b]= ginput(t); >>> text (x, y, txt); 7 >>> endfunction >>> c = uicontextmenu (f); 9 >>> ## create menus in the context menu >>> m1=uimenu("parent",c, 11 >>> "label","Add Text ", >>> "callback " ,{@AddText ,f}); 13 >>> set (f, " uicontextmenu ", c); ✌ ✆ We can use waitfor function too. This is different from the uiwait in sense of conditions. The uiwait function suspends the program execute for a given timeout interval instead of what is going in background. But waitfor suspends program execution till the background conditions is not satisfied. We can update background properties during the program suspension. ✞ 1 >>> f = figure; >>> function AddText(h, e, t) 3 >>> waitfor (t, "timeout ", 5); ## wait for 5 seconds >>> txt = inputdlg ("Enter string"); 5 >>> [x,y,b]= ginput(t); >>> text (x, y, txt); 7 >>> endfunction >>> c = uicontextmenu (f); 9 >>> ## create menus in the context menu >>> m1=uimenu("parent",c,
  • 68. 218 Binary & Digital Operation 11 >>> "label","Add Text ", >>> "callback " ,{@AddText ,f}); 13 >>> set (f, "uicontextmenu ", c); ✌ ✆ 5.6.17 Resume Control The function uiresume resumes the suspend program execution. The handle supplied to this function should be same as the handle supplied to uiwait func- tion. In case of no pending uiwait or invalid handle, this function does nothing. ✞ 1 >>> function Suspend(h, e, t) >>> uiwait(t, 10);## Wait for 10 seconds 3 >>> txt = inputdlg ("Enter string"); >>> [x,y,b]= ginput(t); 5 >>> text (x,y,txt); >>> endfunction 7 >>> function Resume(h, e, t) >>> uiresume (t); ## Resume immediately 9 >>> endfunction >>> g = figure; 11 >>> c = uicontextmenu (g); >>> ## create menus in the context menu 13 >>> m1=uimenu("parent",c, >>> "label","Suspend", 15 >>> "callback " ,{@Suspend ,g}); >>> m2=uimenu("parent",c, 17 >>> "label","Resume", >>> "callback " ,{@Resume ,g}); 19 >>> set (g, "uicontextmenu ", c) ✌ ✆