calqit syntax and function reference

1. Function list and types

Basic math
abs sign cross ceil floor round min max mean range sum prod stdev
sin cos tan asin acos atan sqrt exp log log10 sinh cosh tanh asinh acosh atanh
Matrix creation and properties
zeros ones seq eye diag rand irand randexp err split
size shape reshape nrow ncol isempty isscalar isvector ischar
det inv norm trace
Finding and comparison
all any before find findall strfind strfind_last qfind rfind == ===
Plotting
plot axis fix unfix subplot wipe fill ellipse errbar print
figpos loglog semilogx semilogy replot replot_move text title update
use_colour
Bitmap
loadBitmap snipImage
Mouse
click getmouse onLDown onLUp onMove onDrag onRDown onRUp onLDouble onDragable
Functions related to rational numbers
rat whatis
Further math functions
bnc erf fstep gauss gamma lgamma gammaP gammaQ lor poly
besselj besselj0 besselj1 airy
tophat poisson binomial chebyval
Numerical methods
fzero solve diff differ integ qinteg min fmin fminbrac fft ifft
Data analysis, fitting
mean std variance hist lsfit slf cheby interp linterp smooth SGfilter regularize
Files
cd dir fclose fopen fread fwrite feof load print qload qsave use save type
Sorting and set operations
sort, sortit, unique, issubset, intersect, union, setminus, setxor
Stack, queue and list
stack, queue, list, push, pop, top, item
String
str str2num strfind strfind_last === before lower trim split readtext
Permutations
next_perm, prev_perm, shuffle, shift_round, swap_row, swap_col
Keyboard input
getch getkeyb getline onKey
Miscellaneous
assert disp end numeric_limits pause wait property tic toc whatis

Types

numeric matrix
string matrix
boolean matrix
stack
queue
list
scalar const

2. Syntax and keywords

break
break out of innermost for- or while-loop.
e.g.
j=0; while 1: j += 1; if j>10: break;  disp('j=',j);
see also: breakpoint

breakpoint
breakpoints
To insert a breakpoint in a script finish a statement with ';!'
e.g.
x = 2 ;!
The breakpoint debugging facility is under development. At the time of writing it does nothing except show the line number and pause execution.

clear
clear x undefine a variable called x
clear reset clear variables and functions and restore standard constants
clear everything clears everything and does not restore
clear a b x clear a and b and x (commas can used but are not required)
N.B. clear operations have a different effect at global level than within user functions and loops, see ??clear for more information. To reset the user path see cd.
e.g.
if isdefined('a'): clear a

Further information. Within a user function, and within any scope except global scope, the instruction "clear x" frees memory by reducing x to zero size, without deleting it completely. This can be useful for code clarity, and the compiler will spot subsequent references to x as errors. At global scope, the instruction "clear x" is enacted immediately and completely deletes both x and all user functions which refer to x. [Planned: during a clear you can specify some names of symbols that should not be cleared, by adding a 'keep' clause in brackets, as in]
e.g.

clear reset (keep a b)     # does not clear a or b
clear everything (keep pi)

const
const a = expr declares a constant.
const X,Y,Z creates constants with values X=1, Y=2, Z=2 A constant must be a scalar (i.e. a single number). The expression can be anything involving only numbers, constants and simple functions, which can be evaluated at compile time. Constants are useful for calculations at the command prompt, and within programs they offer some modest speed and memory savings, and improve program readability. You can't use a constant name as an argument name in a function declaration. To list all constants currently declared, use
?consts

e.g.
const a=pi/2; const X,Y,Z;

exit
exit calqit.
see also: quit

exist

see also: isdefined

for
The "for-loop". There are three standard forms: for x = sequence; statement
for x in var; statement
for i, x in var; statement The statement can be a block (a sequence of statements enclosed by {} or indicated by indentation). A sequence has the form either
start : step : stop
or
start : stop The final form, "for i, x in var" specifies that x will take successive values given by the items in some existing variable, and i will take on successive integer values. Its overall effect is the same as for i = 1:var.size(); x = var.i; statement; but with some further features, chiefly that the compiler will prevent you from trying to change the value of i within the loop, and it runs a little faster.
e.g.
for j=1:5; disp(j);
vv = [10 pi 30]; for j, x in vv; disp(j, ',' x); 
vv = list('hello',[42 pi],'there'); for j, x in vv; disp(j, ',' x); 


funclist
use ?funcs or '?func ...' to list function names
e.g.
?funcs     # list user-defined functions
?func a    # list built-in functions whose name begins with a
?func b    # list built-in functions whose name begins with b, etc.
?func all  # list all functions (built-in and user-defined)
see also: vars function

function
User-defined functions
The most common syntax for user-defined functions is either
fname(parlist) := expression for a single-expression function
or
function [return args] = fname(parlist)
statement1
statement2
...
statement
end
for a longer function. You can also use
fname(parlist) := { statement1; statement2; ...; statement; }
and the symbol ::= is used to vectorize. The parlist is a list of parameter names. For example
area(r) := pi r^2;
volume(r,height) := height pi r^2;
If you wish to return more than one value, you must announce this by giving a list of output values after the word "function". For example,
function [mn,mx] = minmax(a)
mn = a.min; mx = a.max
end There are further issues around passing a list or a complex value as a parameter. See ??function for further information.
see also: funclist vectorize functional

Further information. Default values
You can provide scalar numerical default values for parameters using a ':' syntax, as in
f(a, b, c:2, d:0) := blah
Here c and d have default values (2 and 0 respectively), a and b do not. You can then call either f(w,x,y,z) or f(w,x,y) or f(w,x). Once you specify a default value for one parameter, all subsequent parameters must have default values.
Pass by reference
If the compiler determines that a given argument is never modified by the function, then it is passed by reference, and otherwise by default it is passed by value. To force it to be passed by reference use a ^ sign in the function definition as in
f(a, ^m) := blah
Declaration
You can't use a function before it has been defined. When you have a pair of functions that call each other, this leads to a catch-22 situation. It is resolved by allowing functions to be 'declared' before they are 'defined'. A declaration is a statement such as
funcdec [return args] = myfunc(a,b)
This is exactly the same format as a function definition, but the keyword is 'funcdec' not 'function'. You can now refer to myfunc when writing other functions, but you must provide the full definition of myfunc (i.e. including the body) before those other functions are used.
Passing list and complex parameter types
When you pass something like a list or a complex number as an argument to a function, you may need to inform the compiler. The compiler does a pretty good job of interpreting your wishes, but sometimes needs some help. To this end, put a [] immediately after each list parameter, and a * after each complex parameter when declaring the function. e.g.
myfunc(a, b[], c*) := ... # a is ordinary, b is a list, c is complex
an ordinary value can be integer or string or a real number.

help
help get some brief general help
?? get some more help
?name get help on name
??name get more help on name

if
conditional statement
e.g.
a=1; if a==1: disp("it is");
a=1; if a==1: disp("yes it is"); else disp("no it's not");

else
part of conditional statement
see also: if

persistent
Declare that a variable is persistent (i.e. preserved from one function call to the next). This offers some permanent internal memory to any given function.
e.g.
persistent x,y
see also: const global

quit
quit
quits calqit (equivalent to closing the window).

return
return from a function
The keyword "return" is used on its own. The function's return value[s] will have been specified via the function definition.

run

see also: use

set
set(name, value) is used to set parameter values related to various calqit functions. Here name is a string and value is a number.
set lists the names of parameters that can be set
set(name) sets the parameter to its default value
(for operations on mathematical sets, see union, intersect, etc.)
e.g.
set('airy', 1e-8)
set('RGB u', [255 0 0])   # bright red
see also: airy colour

Further information. Internal calculations are always done in double precision (see numeric_limits for more information); set display only affects the precision of the displayed results.

system

see also: sysCommand

sysCommand
sysCommand(str) sends a string command to the operating system. The effect will depend on the local operating system. This command is in principle very powerful and should be used with caution. It can be used to move files around and to rename or even delete them, for example. To get output from your command, use a pipe to place it in a file, then examine the file. To give multiple commands in a single line for Windows cmd use the & symbol. For longer sequences of commands, create a batch file and run that.
e.g.
# This example places a list of the user folder contents into tmp.txt
d = cd; sysCommand(["cd " d " & dir > tmp.txt"])
see also: dir cd

use
use filename runs a script. Default extension is '.clq'.
F9 press the F9 button to run from clipboard
(i.e. run a code snippet selected from calqit or a text editor) If you associate .clq files with calqit, then you can run them from Windows Explorer by a double-click.
see also: F9

while
syntax is "while condition: expr"
e.g.
j=1; while j<10: j*=2
j=1; while j<10: j*=2; disp('j=',j); 
see also: break for

who
To display information about calqit's variables, use ?vars and ?consts. calqit-supplied values of fundamental constants are taken from the latest CODATA least-squares adjustment, as reported on CODATA web site.
see also: help

Type help for basic help.

Further information. Type help for basic help

3. Functions

abs
abs(x) is the absolute value of x. You can also use (|x|).

see also: floor ceil arg

acos
acos(x) is the arc-cosine (inverse cosine) of x.
see also: cos asin atan

acosh
acosh(x) is the arc-cosh (inverse hyperbolic cosine) of x.
see also: cosh

adjoint
To obtain the adjoint of z use z".
e.g.
z = (1 + 1i)magic(3);  z;; ' ';; z"


see also: transpose

all
all(x) is true if all elements of x (or each column of x) are non-zero.
If you want to compare two matrices, then it is quicker to use the === operator, as in "a===b". See 'help =' for more information.
e.g.
all([-3,4,2,8]), all([-3,0,2,8])     # returns 1,0
see also: any find, =.

ans
ans returns the last thing (value, matrix, etc.) which was displayed. (Note: the last thing displayed, not the last thing calculated).
e.g.
a = 77*89;; b = ans/77

any
any(x) is true if an element of x is non-zero.
see also: all find.

arg
arg(z) returns the argument of complex number z.

see also: abs complex

argand
argand(z) plots z on an argand diagram

see also: complex plot

asin
asin(x) is the arc-sine (inverse sine) of x.
see also: sin acos atan

asinh
asinh(x) is the arc-sinh (inverse hyperbolic sine) of x.
see also: sinh

assert
assert(condition) breaks execution if condition is false
assert(condition, a,b,c) is equivalent to
if ~condition: disp(a,b,c); assert(false);
The assert function is typically used for debugging.
e.g.
f(x) := assert(all(x>0),'f requires positive x')
see also: error disp

atan
atan(x) is the arc-tangent (inverse tangent) of x.
see also: tan asin acos

atanh
atanh(x) is the arc-tanh (inverse hyperbolic tangent) of x.
see also: tanh

axis
axis is used to set x- and y-limits for the current plot, and also for adjusting the axes in other ways.
axis(xmin, xmax, ymin, ymax) sets axis limits on current graph.
axis(a) with a = [xmin, xmax, ymin, ymax] is also valid.
Other uses:
e.g.
axis([])   # return the current axis limits
axis []    # ditto
axis(0)    # turn off
axis off   # ditto
axis(1)    # turn on
axis on    # ditto
axis 'equal'   # sets equal x- and y-scales (so circles appear circular)
axis 'full'    # makes the plotted area fill the frame (or the subplot)

Setting axis limits with nothing plotted will also fix the plot 
(you can use unfix to undo this).

You can also use axis to adjust the plotted region and turn x- and y-
axes on and off individually, see further information.

e.g.
plot(sin(x);x,0,5pi); axis(-10,20,-2,2);
v=axis([])  # get the current axis range
axis(5);    # omit the lines through the origin
axis(0);    # turn axes off
see also: grid plot fix unfix replot

Further information. To adjust the presentation of axes on a plot, you call axis with either 1 or 3 arguments, or else with a string argument. The string argument can be one of 'on', 'off', 'equal', 'full'. An integer argument is interpreted as a set of boolean flags. That is, each bit determines a choice, as follows:
e.g.

power 
of 2   value   what it does
0       1      switch on 
1       2      linear scale
2       4      tic marks on left or bottom
3       8      major tic marks on right or top 
4      16      draw an axis line through the origin
5      32      write labels by major ticks
6      64      put tick marks on the zero lines
7     128      unused
8     256      axis equal
9     512      no box around the ploted area
10   1024      axis full

axis(flags)   will adjust just the on, equal, full, no-box flags. 
axis(xflags, yflags, overall) supplies values for the x axis, y axis and others.

e.g.
axis(0); axis 1        # turn off, turn on with default values
axis(1 + 256 + 512)    # on, equal, no box
axis(63-16, 63-16, 1)  # don't draw the lines through the origin
axis(63, 0, 1)         # x axis only
axis(0, 63-16-8, 1)    # y axis only, no zero line, tick on left only


barchart
barchart(x,y) plots a bar chart
barchart(x,y, style) provide a style string
barchart(x,y, w) user-specified width
barchart(x,y, w, style) width and style
Each bar is centred on the corresponding value of x. If w is not specified then the bars all have the same width, taken as the smallest difference between values in the x array. If w is specified it should be either a single value, or an array having the same length as x and y.
e.g.
x = 1:10; barchart(x, sin x)
x = 1:10; barchart(x, sin x, 'r#g 4')
see also: plot

before
before(a,b) or a.before(b) compares two vectors, asking which is "less" in the sense of lexicographic comparison. In other words, if they were words in a dictionary, would a come before b?
e.g.
before('ant','ankle')
a=[1 3 5 7]; b=[1 4 0]; a.before(b)
see also: strfind === operator next_perm

bezier
bezier(p,t) returns cubic bezier curve. Columns of p are the control points. t is either a scalar, indicating the number points on the curve, or a row vector of values in the range 0-1. To use this function, you must first load it into memory with the command
use bezier
e.g.
use bezier
plot( bezier([1 2 4 2; 1 3 4 5], 50) )
see also: bezfit

binomial
binomial([n,p], k) is the binomial distribution function
= bnc(n,k) p{^k(1-p){^(n-k)}}
where n and p and scalar, k can be vector or matrix.
e.g.
n=100; k=1:n; p = binomial([n,0.1],k); barchart(k, p)
see also: poisson bnc gauss

Further information. If k is a binomial-distributed random variable, then its mean value is (n p) and its variance is n p(1-p)

e.g.

n=100; p=0.2; k=0:n; pk = binomial([n,p],k);
av = sum(pk k)    # mean
sum(pk (k-av)^2)  # variance

Further information. binomial([n,p], k) is the probability of obtaining k 'heads' when a weighted coin is tossed n times, (p being the probability of a 'head').

bitmap
- For bitmap loading and manipulation, see
see also: loadBitmap snipImage getpixel

bnc
bnc(n,k) returns the binomial coefficient n!/(k!(n-k)!)
k can be a vector, n cannot. The result is exact for small n,k. For large n,k it uses lgamma for speed. To test the accuracy, you could compare with an explicit product as in
bnc(202,101) , prod(102:202) / 101! # two calculations of the same thing
The exact answer is
360401018730232861668242368169788454233176683658575855546640
(The product method is more accurate but slower, and fails for larger numbers.)
e.g.
for n=0:10; bnc(n, 0:n)      # Pascal's triangle
see also: prod gamma lgamma binomial

cd
cd current directory (or folder)
cd dirname change directory (or folder)
You can also use
cd(d) where d is a string containing the directory name.
cd on its own (with no arguments) returns the current directory
cd ? opens a window where you can select the folder you want
cd on its own returns the path in a string with two added characters at the front: ' \{-'. This is so that Calqit displays the rightmost part of the string (rather than the leftmost) when the window is too narrow to display all of it. To suppress this behaviour, supply an argument, as in, for example,

e.g.
d = cd('.')

If calqit has trouble locating files when you first run it, try:
cd exepath(1)
see also: dir clear exepath

Further information. ---acknowledgement--- The 'cd ?' dialog call was obtained from
https://stackoverflow.com/questions/12034943 /win32-select-directory-dialog-from-c-c,
user avatar SparkyRobinson

cdiag
cdiag(m) diag for complex matrices
see also: diag

ceil
ceil(x) and ceiling(x) round x towards +infinity
see also: floor round

ceiling
ceil(x) and ceiling(x) round x towards +infinity
see also: floor round ??

circle
To plot a circle, use ellipse function
e.g.
circle(x,y,r,style:0) := ellipse([x-r,x+r,y-r,y+r], style)
circle(12,8,3,'r3')
see also: plot ellipse

close
close(n) closes figure window n
close(0) closes all figures (and so does close(-1)).
see also: figpos wipe unfix

color
Colour of plotted lines and texts can be specified either by a single-character code, or by a string giving the colour name, or by RGB codes. For RGB codes use
e.g.
t=seq(0,2pi); cr = 'ABCDEFDGHIJKLMNOPQRSTUVWXYZ'; cr ,= cr.lower
unfix; for j=1:cr.size plot(t+0.1j, sin t, cr.j); fix; 
set('RGB u', [10,40,30])
set('RGB U', [10,10,0])
see also: plot text use_colour show_colours

colour
Colour of plotted lines and texts can be specified either by a single-character code, or by a string giving the colour name, or by RGB codes.
e.g.
t=seq(0,2pi); cr = 'ABCDEFDGHIJKLMNOPQRSTUVWXYZ'; cr ,= cr.lower
unfix; for j=1:cr.size plot(t+0.05j, sin t, cr.j); fix; 
see also: plot text use_colour show_colours

conj
conj(z) returns the complex conjugate of z. This can also be obtained using z" which gives the adjoint.
see also: complex adjoint

cos
cos(x) returns the cosine of x.

see also: sin tan acos cosh

cosh
cosh(x) returns the hyperbolic cosine of x.
cosh(x) = (exp(x) + exp(-x))/2

see also: sinh tanh acosh

createButton
createButton(id) creates a button based on an existing item
createButton(pos) creates a basic button with no text.
createButton(pos, style) creates a button in one of the standard styles.
createButton(pos, style, text) creates a button with text
The style is one of 'a','basic','cross','dot','edit','default','group','h' which can be abbreviated to 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' respectively.
Styles 'e' and 'h' are not strictly buttons: 'e' is an editable text box; 'h' is a fixed text box.
pos = [x,y] or [x,y,width,height] where the values are in terms of the current graph scale.
You can also use
pos = [x,y, 100] or [x,y,width,height, 100] where the trailing 100 indicates that the values are specified as a percentage of the frame. (Note: to specify this case the position vector has either 3 or 5 elements).
e.g.
axis([0 10 0 10]); createButton([1 9 2 0.7], 'b', 'Push me')
createButton([1,8 2 .7], 'c', 'check me')
createButton([1,7 2 .7], 'd', 'option A')
createButton([1,6.4 2 .7], 'd', 'option B');
createButton([1,5 2 .7], 'a', '3 states')
createButton([1,4 3 1], 'e', 'This text can be edited')
createButton([0.9,9.5 2.5 4], 'g', 'Group')
createButton([0, 10, 20,10, 100], 'b', 'bottom left')
createButton([80,100, 20,10, 100], 'b', 'top right')
see also: onButton mouse

cross
- For cross product use a vec b
a and b can be matrices of either 3 rows or 4 columns

see also: vec

cumsum
cumsum(x) returns the cumulative sum of x
see also: sum

daleks
Daleks is a game distributed with calqit. To try it, first locate it in the folder [calqit]clq

data
- Working with data.
If you wish to plot and manipulate experimental data, the usual sequence will be first to prepare your data in a text file, arranged in columns. The entries could be separated by spaces or commas. Then use load to load the data, {=plot} to plot it, and other functions such as slf or {=fft} depending on what you want to do. Here is an example:
e.g.
m = load("mydata.txt")   # don't forget the inverted commas here
plot(m
1, m
print 'myplot' # save the plot to svg file name = "mydata.txt" # you could also set the file name like this m = load name # and then load the data like this For publication-quality output you can use texplot(m
1,m
This method requires some familiarity with LaTeX and Tikz.
see also: load save plot xlabel print texplot

det
det(m) is the determinant of m, where m is a square matrix.
see also: inv LUform solve

diag
If v is a vector and m is a square matrix, then
diag(v) returns a diagonal matrix with v as the main diagonal.
diag(m) does the reverse: it returns the main diagonal.
diag(x,n) and diag(m,n) do the corresponding job for the n'th diagonal. diag only accepts real matrices. For complex matrices use cdiag.
e.g.
diag(1:4);; ' ';; diag(1:4,1)
m = reshape(1:16, 4); diag(m)
see also: eye cdiag

diff
diff(x) returns the vector of 1st differences, i.e. [x.2-x.1, x.3-x.2, ... ]. For a matrix, acts columnwise.
see also: diff2 differ

diff2
diff2(x) returns the vector of 2nd differences, equivalent to diff( diff(x) ).
see also: diff differ

differ
differ(f, vals) calculates df/dx at x=vals for a function f(x)
differ(f, a, vals) df/dx for a function f(a,x)
differ(y ; x,vals) calculates dy/dx at x=vals, where y is an expression
differ(y) for vector y returns an estimate of dy/dx assuming the points are separated by dx=1.
For example, differ([0:4]^2) returns [0 2 4 6 8], since d/dx(x2)=2x.
differ(y,dx) is the same as differ(y)/dx.
The functional version is more accurate. The vector method is faster but only uses the given y values, so is less accurate at the end points, and if the points are widely spaced.

e.g.
x=seq(0,pi); y=sin x; dy=differ(y); dx=x.2-x.1;     # vector method
plot(x, cos(x) - dy/dx)          # illustrate the accuracy
#
dydx=differ(sin, x); plot(x, cos(x) - dydx)         # functional method
differ(poly, [1 1 1], 3)         # d/dx(1+x+x^2) = 1+2x = 7 at x=3
see also: integ, binteg

Further information. Differ uses the five-point method:
df/dx = [ 8(f(x+h)-f(x-h)) - (f(x+2h)-f(x-2h)) ]/12h

dir
dir list current directory contents.
dir p list files p, or contents of p.
By default the list is shown as a table. To display it vertically, add a ':' after the command, as for example "dir :" or "dir *.txt :". To suppress display, add '' as in "d = dir ''".
e.g.
dir
dir :
dir *.clq
dir *.clq :
d = dir *.clq ''
see also: cd load save

disp
General-purpose display function. disp(x) displays all the values in x. The return value is []. By default disp produces a newline, but you can suppress this by finishing with an empty string: see the first example.
e.g.
disp('this is all',''); disp(' on one line');
x=1; disp('x=', x, ', exp(x)=', exp(x));
see also: dispfile messageBox

dispfile
dispfile(name) Display a file. The default file type is '.clq'.
dispfile(name, linenum) Display the lines near linenum in file.
see also: disp cd dir

dragable
dragable(id, limits) declares an existing plotable item to be dragable; this means the user can click and drag the item using the mouse.
limits = [xmin, xmax, ymin, ymax] restricts the allowed movement.
dragable(id) adopts the current axis limits as limits.
Upon clicking a dragable item, onButton(id,xy) is called.
Upon draging a dragable item, onDragable(xy,id) is called.
e.g.
axis([0 9 0 9]); p=plot(2,2,'go5 2'); dragable(p,[1 5 0 3]);
axis([0 9 0 9]); q=plot(2,1,'bs5'); dragable(q,[1 5 1 1]);
see also: mouse onDragable createButton replot onLDown onDrag

eigval
eigval(m) returns the eigenvalues of real symmetric matrix m
e.g.
m = 1 / [1:4; 2:5; 3:6; 4:7];  # Hilbert matrix of order 4
eigval(m)      # ans should be  1.5002 0.16914 0.0067383 9.6702e-5
see also: eigvec eigvv

eigvec
v = eigvec(m) returns the eigenvectors of real symmetric matrix m.
Each column of v is a normalized eigenvector.
The vectors are sorted in order of decreasing eigenvalue. If you want both eigenvectors and eigenvalues, then use eigvv.
e.g.
eigvec([0 1;1 0]) * sqrt 2     # a simple example
m = 1 / [1:4; 2:5; 3:6; 4:7];  # Hilbert matrix of order 4
v = m.eigvec; D = v' . m . v   # answer should be diagonal
(|D|) > 3*numeric_limits[]     # indicate elements of size > 3*eps
[lam,v] = m.eigvv              # using eigvv instead
see also: eigval eigvv

eigvv
[lam,v] = eigvv(m) returns the eigenvalues and eigenvectors of real symmetric matrix m.
Each column of v is a normalized eigenvector.
Note, the function assumes the matrix is symmetric: this is not checked. If you supply a non-symmetric matrix the outcome is often reasonable but is not guaranteed.
e.g.
[lam,v] = eigvv([0 1;1 0])     # a simple example   
m = 1 / [1:4; 2:5; 3:6; 4:7];  # Hilbert matrix of order 4
[lam,v] = m.eigvv
see also: eigval eigvec

ellipse
ellipse(rect) plots an ellipse in the given rectangle,
where rect = [x1 x2 y1 y2].
ellipse(rect, style) provides style information as well.
e.g.
ellipse([10,20,5,9]);
fix; ellipse([12,15,6,7],'r4');
see also: plot

end
In an index to a vector or matrix, end refers to the size of the vector or the number of rows or columns of the matrix. Thus
v[3:end] means elements 3 to y.size
m[2,4:end] means columns 4 to ncol of row 2
m[5:end, :] means rows 5 to nrow
end can also be used to terminate function definitions, as an alternative to using {} braces (this can aid code readability): see ?function.
see also: top pop

erf
erf(x) is the error function (the area under the normal distribution)
erf(x) = (2/sqtp) int0{^x} exp(-t{^2}) dt.
= gammaP(1/2, x^2) (x >= 0)
e.g.
plot(erf, -3,3)
see also: gauss normal gammaP erfc erfinv

erfc
erfc(x) = 1 - erf(x) is the complimentary error function
see also: erf gammaP erfinv

erfinv
erfinv(x) is the inverse error function.
erfinv(1-p) is the probit function, which converts one-tailed probability p to z-score z.+
e.g.
plot(erfinv, 0.001,0.999)
z = erfinv(0.9); integ(gauss, 1/sqrt(2pi), [z, inf])
see also: gammaP erfc erf

err
err(sig, n) returns n normally distributed random numbers
err(n) assumes sig = 1
err(sig, [nr, nc]) fills a matrix
e.g.
plot(1:10, err(10), '+');
[f,bin,ph]=hist( err(0.1,1000) ); plot(ph);
see also: rand

errorbar

see also: errbar

errbar
errbar(x,y,dy) plots error bars
e.g.
n=50;x=1:n; y=10sin(x/5)+err(n); dy=rand(n); errbar(x,y,dy);
see also: plot

errfit
errfit(func, a, x, y)
***errfit is under development and not yet implemented---sorry! ***
errfit is used in combination with lsfit to find the uncertainties on fitted parameter values in least-squares curve fitting. The simplest usage is
a = lsfit(func, a0, x, y)
da = errfit(func, a, x, y)
That is, first one uses lsfit to check the fitting is working ok, then one may as well pass the best fit paramater values to errfit in order to give it a good initial guess. It returns the uncertainties.
The method employed is a bootstrap (see, e.g. Numerical Recipes chapter 15): new data sets are generated from the original one by selecting points at random (with replacement, i.e. you can draw the same point twice), and then these are fitted. One thus obtains a (large) set of fitted values for each parameter. The routine plots the histogram of each set and returns the standard deviation. The method is valid if the errors on data points are independent and identically distributed, and the function is well behaved. Oh dear, that means it is almost never strictly valid. Nevertheless it gives you a good feel for the possible variability in your answers, and it is a LOT better than just blindly trusting the covariance matrix.
If just two parameters are floating, the routine also produces a figure showing a scatter plot and 68% confidence limits. This enables one to check for correlations and/or non-Gaussian behaviour.
e.g.
x=[0:0.2:4]; y=poly([1 2 3], x) + err(x.size);
a = lsfit(poly, [0 0 0], x,y); da = errfit(poly, a, x, y);
see also: lsfit slf

Further information. If the residuals are randomly distributed, and if that distribution is the normal distribution, and you have plenty of data, then you can extract statistical errors on the fitted parameters with confidence. However these conditions are almost never met in practice! The curve you are fitting is based on your best guess of what the experiment is doing, but you never know that for sure: every scan and every detector has systematic error (e.g. non-linearity) at some level which you have not so far been able to rule out. Some systematic effects can be ruled out to high accuracy, of course, but it is very often the case that there remains the possibility of systematic error at the same level as the statistical error in the data you are fitting. If the fitting procedure somehow knew about the systematic error function, then it would return residuals which were non-random and which clearly revealed the effect not modelled by your fitting function. However, lsfit is not omniscient and can't do that. Instead it pushes your fitting function around, trying to make it fit the data, leaving residuals distributed roughly equally above and below the line (minimising the squares), so looking fairly random, thus hiding the underlying effect that was not captured by your model. The point is that this pushing around shoves the "best fit" parameter values over to some systematically wrong answer.
The scientific journals are full of underestimated experimental errors. If a result has been obtained by "reasonably good" curve fitting but without careful ellimination of systematic error, then a good rule of thumb is that the total experimental uncertainty on any given parameter is twice the statistical error reported by least squares methods.

error
error(level) or error(level, message)
display a warning message (when level=0) or throw an error (when level > 0)
see also: assert

eval
eval(s) evaluate a string as a calqit expression. All variables referred to in the string are assumed to be global variables. N.B. multiple calls using the same string will re-use the first compiled version.
e.g.
eval("1+1")
disp("type an expr: ",''); disp('value = ', eval(getline));
see also: table

Further information. evaluating the expression. In order to allow an efficiency improvement, the compilation step is omitted when the string is completely unchanged since the last call to eval---instead the previously compiled expression is used. This might not be what you want, for example if you have meanwhile modified the type of a variable so that the meaning of the expression changes. To force a re-compile you can use
eval(''); eval(s);

exepath
exepath returns the path to where Calqit was invoked
exepath(0) does the same
exepath(1) returns the path of the Calqit executable (application)

see also: cd

exp
exp(x) is the exponential function

see also: log

eye
eye(n) returns the (n x n) identity matrix. eye(n,d) returns an (n x n) matrix with 1s on the diagonals indicated by d.
e.g.
eye(4)      # 4x4 identity matrix
eye(4,0:4)  # upper triangle of 1s
see also: zero diag

fclose
fclose(fid) closes file id
fclose(-1) closes all files
see also: fopen fread fwrite load save

feof
feof(fid) returns 1 if the end of input file fid has been reached
see also: fopen fread

fft
fft(y) returns the fast Fourier transform of y. The array y can be real or complex. The return value will be complex. Let n be the number of points in y. If n is not a power of 2, then y is first padded with zeros, giving np points. The Fourier component at index number (k+1) has wavelength np/k. You may want to divide the result by sqrt(np).
e.g.
# This example creates a symmetric function, giving a real transform
r = ones(1,128); r[12:118] = 0; plot(1:128,r)
ff = fft(r); plot(1:128, ff.real, '.')
# This example illustrates a noisy pair of waves
x =-511:512; r = sin(x) + 0.5 sin(2x) + err(1, x.size)
k = [512:1024, 1:511]; f = fft(r[k]); 
subplot(1,2); plot(x,r); subplot(2,2); plot(k, abs(f))
see also: ifft

ifft
ifft(y) returns the inverse fast Fourier transform of y.
see also: fft

figpos
figpos(...) is used to obtain and set the position and size of a figure on screen.
figpos(n) returns x1,x2,y1,y2 for figure n
figpos(x1,x2,y1,y2) sets position and size, as a p.
figpos(x1,x2,y1,y2, 0) sets calqit's own window.
If the numbers x1,x2,y1,y2 are greater than 1 then it is assumed they refer to positions in pixels. If they are between 0 and 1 then they refer to fractions of the screen width or height.
You can also use parameters like those for subplot:
figpos(i,n) make the figure position i of n
figpos(nrow,ncol,i) make i'th position in an array of figures
e.g.
figpos(500,1000,1,500);
figpos(0,0.25,0.25,0.5);
see also: plot subplot

figure
figure(n) opens a new figure, or switches graphics input/output to an existing figure
see also: figpos plot wipe

fill
fill(...) is like the plot command, but fills a region with colour instead of plotting a line. It is equivalent to using plot with the '#' style character, followed by fix. You can use replot(...) to change a filled region.
e.g.
fill([0 1 1 0; 0 0 1 1],'g');
x=seq(0,2pi); fill(x, sin x,'G');
plot(sin,0,2pi,'#G');        # has the same effect
see also: plot colour

find
find(x) returns the index of the first non-zero value in x, or zero if none is found. For a matrix it is applied to each column. This uses a slow (O(n)) exhaustive search of a disordered list. For an ordererd list, use qfind.
see also: qfind rfind findall strfind

findall
findall(x) returns indices of all non-zero values in x, or [] if none are found.
This uses a slow (O(n)) exhaustive search of a disordered list. For an ordererd list, consider using qfind.
see also: qfind find rfind any all strfind

findstr
findstr is a synonym for strfind
see also: strfind

fix
fix is used to allow plotting of multiple curves on the same graph.
A call to plot(...) will delete the current graph and start a fresh one, unless it is preceded by a call to fix (this is like Matlab's `hold on').
e.g.
plot(sin x;x,0,pi); fix; plot(cos x;x,0,pi,',');
see also: unfix axis subplot

floor
floor(x) round x towards -infinity
see also: ceiling round

fmin
Function minimisation. fmin(func,x0) or fmin(func,a,x0) gives the x-location of a minimum value of func near x0. You can also supply a further options parameter, and obtain the function value using [x,y] = fmin(func,x0).
fmin(expr;x,x0) is also legal. See further information to understand the use of x0 and how to set the precision.
e.g.
fmin(sin,0)        # gives -pi/2 to precision 1e-8
fmin(besselj,3,8)
fmin(x sin x; x,4)  

see also: min minind max mean std fmin fminbrac

Further information. 1-dimensional minimisation The start point x0 can either be a single value or a pair or a triple.
single value: start at x0, look nearby, expand the search till a min is found.
pair: start at these values, use them to guess the next step. This means the pair typically does NOT bracket the minimum.
triple: similar to pair, but now the first and last may bracket the minimum.
The default relative tolerance in the x position is 1e-8. You can supply another value using
min(func, a, x0, tol) or
min(func, x0, [], tol) where the [] is required to prevent ambiguity. (The method used is Brent's method: try a parabolic fit to jump near to the minimum if possible, if this fails then use a robust golden section search.) For further information on function minimisation, see ?fmin and ??fmin. General function minimisation calqit provides 3 ways to find a minimum of a function:
i. fmin 1-dimensional minimisation using Brent's method,
n-dimensional using downhill simplex (Nelder and Mead), with or without annealing
ii. qmin n-dimensional using Powell's direction set method
iii. linmin minimise along a line in parameter space
Calling qmin with a function of one parameter is the same as using fmin.
It may be wise to first locate a minimum roughly. In one dimension this can be done using fminbrac.
Powell's method is quadratically converging once you are near the minimum. It is best used when the landscape is simple, e.g. to tweak a result found using fmin. The downhill simplex method is better if the landscape is complicated. Both these are guaranteed to find a local minimum. To try to find a global minimum, use the simulated annealing option to fmin.

fminbrac
fminbrac(func, x0) returns a set of three x values that bracket a minimum of the function.
fminbrac(func, a, x0) does the same for func(a,x)
You should supply an initial point or pair of points in x0. If you provide a pair, they should NOT bracket the minimum, but rather both should be on the same side of it.
e.g.
abc = fminbrac(cos, 1); plot(abc, cos(abc), '+8 :');
see also: min fmin qmin

fopen
fid = fopen(filename,mode) open a file for reading or writing
mode can be one of:
r, w, a meaning read, write, append text
rt, wt, at synonyms for the above
rb, wb, ab read, write append binary bytes
b synonym for rb
default rt unspecified mode means read text
q adding a q (for 'quiet') to the end of the mode string
suppresses the "file not found" warning.
! adding an exclamation mark causes the program to halt
if the file cannot be opened.
r.ext w.ext You can also specify a default extension (see examples).
fopen is used with either fread or fwrite for general file io. If you simply want to read or write matrices or data, perhaps with some accompanying header text, consider using load and save which are more efficient and don't need fopen, fclose.
e.g.
fid = fopen('myfile.txt')         
nm = 'myfile'; fid = fopen(nm, 'r.txt')  # specify a default extension
fid = fopen('myfile.txt','q') or 'fopen failed';;
fid = fopen('outfile.txt','w')         
see also: fread fwrite fclose load save readcsv

four
- For fourier transform, see
see also: fft ifft

fourier
- For fourier transform, see
see also: fft ifft

fread
fread(fid) read one line from a text file or one byte from a binary file
fread(fid, n) read n bytes from a binary file
see also: fopen fclose readtext load save feof

fstep
fstep(x) step function (Heaviside function) = (0,0.5,1) for (x<0, x=0, x>0)
see also: sign tophat

fwrite
fwrite(fid, item) write a string to text file or a set of bytes to a binary file. By default, for text output the item is written followed by a newline. To suppress the newline, append the character '
e.g.
fwrite(fid, 'Hello 

see also: fopen fclose load save

fzero
fzero is used to find all the zeros in a set of data, or a single zero of a function.
fzero(f,xguess) where f is a function, returns the x position of a zero of f
fzero(f,xlim) ditto, where xlim=[x1,x2] initially brackets the zero.
fzero(f,a,xlim) treats a function f(a,x)
fzero(expr;x,xlim) treats an expression
fzero(y,x) where y,x are vectors, returns the x positions of zero-crossings in y,
obtained by linear interpolation between the nearest data points
fzero(y) does the same, using the values 1:n for x

e.g.
x=seq(0,10,100); fzero(sin x, x)  # rough zeros of sin(x)
fzero(tan x -1/x; x, [0.5,1])     # returns a solution of tan(x)=1/x
a=1:4; plot(poly(a,x); x,-1,1);   # plot a cubic equation
fzero(poly,a, [-1,1])             # find the root
fzero(poly(a,x); x,[-1,1])        # same thing
see also: qfind functional

Further information. fzero(f,a, x,tol) sets the tolerance (default is 1e-10)
fzero(f,x,[],tol) use [] when a is not supplied
Root-finding method By default, fzero uses Ridder's method: a judicious combination of binary search and logarithmic Newton-Raphson. This is best when each function evaluation is costly. However, if the function can treat a vector of values almost as fast as a scalar, then it may be quicker to use an 'n-section' method: evaluate at n points, use binary search to find the zero crossing, divide the range by n, and iterate. To request this, supply n as a second value in the final parameter.
e.g.

a=1:4; fzero(poly,a,[-1,1],[1e-10, 101]) # here n = 101
 

lgamma
lgamma(x) = ln( abs(gamma(x)) ).
see also: gamma gammaP gammaQ

gamma
gamma(x) is the Gamma function
G(x) = int{_0{^ inf} t{^(x-1)}e{^-t} dt}
= (x-1)! for integer x
You can also use G(x) and
see also: lgamma gammaP gammaQ zeta

gammaP
gammaP(a,x) is the "incomplete Gamma function"
= (1/G(a)) int0{^ x} t{^(a-1)}e{^-t} dt
The function rises from 0 to 1 in a region near x = a-1 with width sqrt(a). It has various applications in statistics, since it is related to the error function.
e.g.
plot(gammaP(5,x); x,0,10);
see also: gamma gammaQ erf

gammaQ
gammaQ(a,x) = 1 - gammaP(a,x)
= (1/G(a)) integral_[x to inf] t(a-1)e{^-t} dt
This is useful for intepreting least squares fitting results, see chisq.
e.g.
plot(gammaQ(5,x); x,0,10);
see also: gamma gammaP chisq slf

gauss
gauss(par,x) returns Gaussian function evaluated at points x.
par = [A, sd, x0, y0] gives the parameters. If you supply a parameter vector with fewer elements, then default values are used for those not supplied. The default values are [1,1,0,0]. par can also be omitted altogether: gauss(x) returns exp(-x^2 /2) (i.e. a function whose height is 1 and standard deviation is 1).
To normalize, use A = 1/(sig sqrt(2pi)) Full definition:
y0 + A exp(-(x-x{_0} ){^2} /2
e.g.
plot( gauss([2,0.5,1,0.25],x); x,-1,3 );
see also: lor erf err

Further information. The area under the normal distribution between +/- erf(1/sqrt(2)) = 68.27%.

get
get(i) returns information associated with graphics item i. For example, if i is a check-box then get(i) returns the check status. If i is a plotted line then get(i) returns the y data.
e.g.
axis([0 10 0 10]); id=createButton([1,9 1.5 .6], 'c', 'check')
get(id)
see also: createButton set

getch
getch Waits for the user to hit a key on the keyboard, displays and returns the character. Use this to get single-character input at the calqit window.
e.g.
disp('yes or no?', ''); ch = getch;
see also: getline getkeyb

getclick
getclick(n) waits for a click in window n
This enables your program to wait for responses from the user.
Returns the x,y mouse coordinates of the click.
e.g.
figpos(1); disp('click the figure'); tic; getclick(1); toc
# make sure you click the figure window!
see also: mouse pause getmouse onLDown onLUp getkeyb

getkeyb
getkeyb This is used to get keyboard input from the figure window. c=getkeyb returns the character code of the key currently pressed down. If no key is down, then returns 0. The following example shows how to use this to respond to the left/right arrow keys. It keeps running until you hit return (in the figure window).
e.g.
const RET=13; const LEFT=37; const RIGHT=39;
x=0; p=plot(x,0,'^Bo20 2'); axis(100[-1 1 -1 1]);
dx(k):= k==LEFT? -0.01 :: (k==RIGHT? 0.01 :: 0)
k=0; while k~=13:k=getkeyb; x += dx(k); replot(p,x,0); 
see also: getch getline getmouse onKey

getline
s = getline(prompt); is used to get keyboard input, until the user hits the "return" or "enter" key. prompt is a string which you provide (it may be empty). Don't forget the semicolon or the displayed result may look a little odd.
e.g.
s = getline('enter a string:'); disp('You wrote "', s, '".');
see also: getch getkeyb

getmouse
getmouse(n) returns mouse status:
n is either an integer index or a character code, as follows:
n=0 reset the click status (see n=5)
n=1,2 x,y mouse x,y
n=3,4 l,r left, right button is down
n=5 c clicked since last call to getmouse(0)
n=6,7 X,Y x,y location when left button went down
n=8 D left button was double-clicked
n=9 i get id of dragable item
n=10 m memory: retrieve information (see setmouse)
n=11 f retrieve return value of last mouse function (see onLDown)
n=12 F get frame number where the mouse is currently active
n=13 k retrieve keyboard key which is currently down
getmouse(n) for non-empty n also forces an update of the window (see update)
getmouse([]) returns x,y without update: this is faster, use it when the window was already recently updated.
e.g.
xy = getmouse([1,2])
xy = getmouse('xy')
clicked = getmouse('c')
buttons = getmouse([3,4])
everything = getmouse(1:9)
see also: getclick replot demo setmouse onLDown

Further information. getmouse('m') (or getmouse(10)) is used to retrieve a value previously provided using setmouse. For example, use it to send information between mouse functions. In onLDown you could calculate something like an id number, and store it using setmouse(id). Then subsequently in onDrag you could find out what was clicked by calling getmouse('m').

hist
hist(x,n) returns frequencies for a histogram of x using n bins
h = hist(x) returns bins and frequencies in the form h = [bins; f]
hist(x,n) n is number of bins
hist(x,bin) user-provided set of bins
e.g.
x=err(1,1000); h=hist(x); histplot(h);
w = h[1,2]-h[1,1]; barchart(h
1 + w/2, h
see also: barchart histplot

Further information. Suppose you specify "f = hist(x,bin)", then:
every x below bin[2] goes into f[1]
every x >= bin[2] and below bin[3] goes into f[2]
...
every x >= bin[n] goes into f[n]

histplot
histplot is a resource used for plotting histograms. Further help will appear once you have used the function hist.

hold

see also: fix unfix

imag
imag(z) returns the imaginary part of z, as a real number.
see also: real complex

index
Indexing of vectors and matrices.
Indexing is mostly commonly done using integers as follows:
x.i x[i] the i'th element
xi x[i,:] the i'th row
x
i x[:,i] the i'th column
In each pair the first version is more succinct, the second version is also valid. For a matrix you can also get a row or a column using string indexing, as follows. If headings is an array of strings and name is a single string then
m[headings, name] refers to the column indicated by name.
m[name, headings] refers to the row indicated by name.
This string-based indexing method involves searching through the strings so will be slow for very large tables, but it is convenient otherwise.
e.g.
m=reshape(1:30 mod 12,[10,3]); cols = ['day  ';'month';'year ']
m[cols, 'day']
see also: dot, readcsv

integ
integ(func, xlim)
integ(func, a, xlim)
calculates the integral of func(x) or func(a,x) over the range xlim=[x1, x2]
You can also specify tol and a maximum number of iterations, as in
integ(func, xlim, '', [tol, niter])
Default values are 1e-9 and 10. Only increase niter with caution (e.g. by 1 or 2) or the function will slow down greatly: each iteration is a recursive division into finer steps.
For integrals over an infinite interval, the precision is less well controlled, but it is high for well-behaved functions as long as there is not a very long tail, or a long oscillating tail.
See qinteg for a faster but less versatile function.
e.g.
integ(sin, [0,pi])           # answer should be 2, 
integ(poly, [1 2 3], [-2,2]) # answer should be 20
integ(1/x^2; x, [1,inf])     # answer should be 1
integ(lor, [], [-inf, inf])      # area under Lorentzian curve
integ(1//sqrt(x)(1+x); x, [1e-300,inf])   # works ok (ans should be pi)
integ(sinc, [0, inf])                     # fails (ans should be pi/2)
# (the second case can be treated instead by choosing a large finite range)
see also: qinteg, binteg, cumsum, table, differ

interp
interp(data, x) performs cubic interpolation
data should be in the form of two columns containing x and y values
x is the point or set of points at which the interpolated value is required.
At least 2 data points must be supplied.
For linear interpolation, use linterp.
e.g.
xd=(1:5)'; yd=cos xd; x=seq(0,6,50); y=interp([xd,yd],x);
plot(x,y,'. 4', xd,yd,'ro', x,cos(x),'=b');
see also: linterp smooth

Further information. The cubic interpolation function is continuous and has a continuous first derivitive. It is fitted to the four data points bracketing any given value of x, such that the curve goes through the middle two points and has a gradient there obtained from the pairs (0,2) and (1,3) respectively, where the points are labelled (0,1,2,3). This is a form of Catmull-Rom spline. This should not be used for extrapolation except over very short excursions. If you are dealing with noisy data you should combine this with smoothing. However it may be better to fit a suitably chosen curve to the whole data set using lsfit.

intersect
intersect(a,b) set intersection. a and b must be already sorted.
e.g.
a = 1:5; b = 3:6; a.intersect(b)
see also: unique issubset union setminus setxor

inv
inv(m) is the inverse of m, where m is a square matrix.
inv('') is the inverse of the working matrix.
N.B. if your interest in inv(m) is in order to solve a set of simultaneous equations, then it is faster and more accurate to use solve.
e.g.
m = rand(3,3); m . inv(m)
see also: solve LUform det

irand
irand(n) returns a random integer in the range 0 to n-1.
irand(n, m) returns a list of m random integers in the range 0 to n-1.
irand(n, [nr,nc]) fills a matrix.

e.g.
irand(10, [5,7])
see also: rand

isboolean
isboolean(x) reports if x is boolean
see also: type ischar

ischar
ischar(x) reports if x is a character string
see also: type isboolean

isdefined
isdefined(name) where name is a string, returns one of the following:
0 the name is unrecognized
1 it is the name of a const
2 it is a symbol
3 it is a function
Note, a name that was not defined at compile time may be defined by the time the code is run.
e.g.
isdefined('pi')
see also: types isscalar isvector isempty ischar

Further information. The following code snippet always displays 'yes', because the compiler defines 'blah' as soon as it compiles the "blah='yes'" clause, which happens before the if statement is run:
e.g.

if isdefined('blah'):  blah='yes';; 

isempty
isempty(a) returns true if a has size 0.
see also: isscalar isvector isdefined

isnum
isnum(s) returns true if the string s can be interpreted as a number
see also: str2num

isprime
isprime(n) returns true if and only if n is prime and not too large
see also: primeFactors primeList

isscalar
isscalar(a) returns true if a has size 1.
see also: isempty isvector isdefined

isstring
To test if a variable is of string tpye, use ischar
see also: ischar type

issubset
issubset(a,b) for sorted vectors a,b returns true if a is a subset of b
see also: sort sortit unique intersect union setminus setxor

isvector
isvector(a) returns true is a has a single row or column. N.B. for the empty set, isscalar([]) is false, but isvector([]) is true. Also, isvector evaluates true for scalars: it is only false for matrices.
see also: isempty isscalar

join
x.join gathers a list into a single vector
x.join(s) also inserts separator s between items
see also: split list

key
keyed indexing.
You can use strings to index the rows of columns of a matrix.
This provides a functionality somewhat like a 'DataFrame' in python's 'Pandas' module.
If m is a matrix, keylist is a matrix of strings and key is a string then
m[keylist, key] gives the column indicated by key
m[key, keylist] gives the row indicated by key.
e.g.
m = reshape(1:12, [4,3]); keys=['day  ';'month';'year ']; m[keys,'day']

kron

see also: tensor

kronecker

see also: tensor

linterp
linterp(data, x) performs linear interpolation
data should be in the form of two columns containing x and y values
x is the point or set of points at which the interpolated value is required.

e.g.
xd=(1:5)%; yd=cos xd; x=seq(0,6,50); y=linterp([xd,yd],x);
plot(x,y,'. 4', xd,yd,'o');
see also: interp smooth regularize

list
a = list() declares an empty list.
a = list(n) (for scalar n) declares a list of n empty items
a = list(x,y,z) declares a list and puts the three items in it
A list is an array of items. Each item can be any type of calqit object, such as a matrix, string, or another list. Operations involving an item in a list are restricted (because the compiler cannot predict the type). If you meet such an issue, then first assign the item to a (non-list) variable, and then that variable. (To display lists of variables or functions, see ?vars and ?func)
e.g.
a = list(); a[1] = [3 4 5]; a[2] = 'hello'; a[3] = diag(a[1]);
b = list([3 4 5], 'hello', eye[3])
a.2 = [];  # erase 2nd element
a.2 = -[]; # set 2nd element equal to the empty set
see also: item top push pop readtext dir

Further information. To sort a list, you could first copy the items to a matrix (using pad to make them all the same length), then use sortrows, then copy them back (using trim).

lg2
lg2(x) returns the logarithm to base 2 of x (= ln x / ln 2)
see also: log log10

linspace
linspace is an alternative name for seq
see also: seq

load
load is used to load numerical data from a text file.
m = load(filename) load a matrix
[a,b,c] = load(filename) load first three columns into a,b,c
The file can have a header, which will be ignored (to be precise, the routine starts reading numbers from the first line in the file which begins (after possible space and commas) with a digit or '.D' or '-D' or '-.' where D is a digit). Also, any text (for example a comment at the end of each line) will be ignored. The numbers in the file can be separated by spaces or commas or tabs or a combination.
see also: save fread readcsv

Further information. Here is an example of the file format that load is designed to work with:

e.g.

My text file. This is some header text at the
top the file. Just make sure the lines don't
begin with a number or - or a dot.
0.34 6 45   the first row of data
0.45 2 3.4  the 2nd row
0.32 4 0
0.4  3 5    these text comments will all be ignored
see also: save readcsv

loadBitmap
loadBitmap(filename) loads a bitmap image and returns the information [id, width, height] The bitmap is shown in the figure window with its top left corner at (0,0). You can then use replot_move to place it somewhere else.
see also: snipImage

log
log(x) or ln(x) natural logarithm of x
see also: exp lg2 log10

log10
log10(x) is the logarithm to base 10 of x (same as ln x / ln 10)
see also: ln lg2

loglog
Syntax like plot, but plots on logarithmic scales. Negative data points are placed at the edge of the figure window.
e.g.
loglog(x^4;x,1,90);
see also: plot semilogy semilogx

logspace
logspace(start, stop)
logspace(start, stop, n)
Returns a sequence of powers of 10.
Equivalent to 10^seq(start, stop) or 10^seq(start, stop, n)
e.g.
logspace(-3,2,6)
logspace(-3,3)
see also: seq linspace

semilogx
semilogx(...) Syntax like plot, but x axis has a logarithmic scale.
e.g.
semilogx(x;x,1,90);
see also: plot loglog semilogy

semilogy
semilogy(...) syntax like plot, but y axis has a logarithmic scale.
e.g.
semilogy(exp(-x^2);x,-3,3);
see also: plot loglog semilogx

lor
lor(par,x) returns Lorentzian function evaluated at points x.
par = [A, FWHM, x0, y0] gives the parameters.
If you supply a parameter vector with fewer elements, then default values are used for those not supplied. The default values are [1,1,0,0], so for example lor(x) is 1/(4x^2 + 1)
Full definition: y0 + A Gamma^2 / (4(x-x_0 )^2 +
e.g.
plot( lor(2,x); x,-4,4 );
plot( lor([2,0.5,1,0.25],x); x,-1,3 );
see also: gauss

lower
lower(s) converts upper to lower case in a string

LUform
LUform(m) returns the LU form of a row permutation of m.
[lu, perm, s] = LUform(m) returns the permutation as well, with s=+1 or -1 for an even or odd number of swaps.
The LU form of a square matrix M is a pair of matrices L and U such that M = L.U, where L is lower- and U is upper-triangular, respectively. The function returns them in the form of a single matrix A whose upper and lower triangles are U and L (to be precise, U is the upper triangle, L is the lower triangle with the diagonal replaced by 1s).
To extract the upper triangle, use, for example, A*eye(n,0:n).
e.g.
m = rand(4,4); [lu,perm,s]=LUform(m); 
l = eye(4,-4:-1)*lu + eye(4); u = eye(4,0:4)*lu;
m[perm, 1:4] - l . u
see also: solve inv det

lsfit
a = lsfit(func, a0, x,y) least squares fit of func(a,x) to data x,y
a = lsfit(func, a0, x,y,sig) with data uncertainties sig.
Also:
a = lsfit(func, a0, floating, x,y)
a = lsfit(func, a0, floating, x,y,sig)
a = lsfit(func, a0, floating, x,y,sig, options)
a = lsfit(func, a0, floating, x,y,[], options)
a = lsfit(func, a0, x,y,[], options)

e.g.
x=seq(-5,5,50); y=gauss([3 0.8 2 0],x) + err(0.1,x.size);
a0 = [1 1 1 1]; sig = 0.1+0x;  # initial guess; 
a = lsfit(gauss, a0, x,y,sig)
see also: slf, chisq, rescale

Further information. options parameter is [doplot, tol] where
doplot = 2 (default) plot and also list the best-fit values
1 plot, but do not list the values
0 no plot.
tol (default value 1e-6) is the fractional change in chi^2 that signals convergence.
Here is another example (you may need to clear f first):
f(a,x) := gauss([a(1:3), a.7],x) + gauss(a(4:7), x);
# This defines a sum of two gaussians on a common background.
x=seq(-5,5,50); y=f([10 1 -3, 20 0.5 1, 0.1], x) + err(x.size);
sig = 1+0x; a0 = [15 1 -2 15 1 2 1]; # provide a very rough hint
a = lsfit(f, a0, x,y)
Method: Levenberg-Marquardt. The code estimates the derivatives df/da_j by the simple difference (f(a+da)-f(a))/da, with da = 1e-8. This means you should scale the parameters a so that this is a reasonable estimate, i.e. d^2f/da^2 is not too large.
Goodness of fit See chisq for information on the chi^2 and Q statistics. If you request a second output parameter, as in
[a, info] = lsfit(f, a0, x,y)
then lsfit returns info = [ To get an indication of the uncertainties on the fitted parameter values, use errfit. However, be warned: interpreting fitted curves can involve subtleties. See errfit for more information.

magic
magic(n) returns a magic square of order n.
e.g.
magic(3);; '--';; magic(4)

max
max(v) for a vector gives the highest value in v.
max(m) for a matrix gives the highest value in each column.
see also: maxind min mean range

maxind
maxind(x) return the index of the largest item in x
see also: max min minind

mean
a.mean gives the average of the elements of a (=a.sum/a.size)
see also: sum size std

menu
menu(headings, submenus) attaches a menu system to the current figure. headings must be a list of strings or a string matrix. submenus must be a list of lists, or a list of string matrices. Each item in a menu should be specified as "text->command" where text is displayed in the menu, and command is a command string which is passed to Calqit when the menu item is chosen.
e.g.
headings = ['File';'Help']
m1=list( '&cd->cd', '&Dir->dir' );
m2=list( '&Help->??', '&Cos->plot(cos,0,9)' );
menu(headings, list(m1,m2));

messageBox
messageBox(s) displays a box with a given message.

e.g.
messageBox('hello there')
see also: disp

min
min(v) for a vector gives the lowest value in v.
min(m) for a matrix gives the lowest value in each column.
e.g.
x=(-3:3)^2; min(x)
see also: minind max mean fmin fminbrac

minind
minind(x) return the index of the smallest item in x
see also: min max maxind

mod
x mod n means x modulo n, i.e. the remainder after x is divided by n.

nchoosek
- For binomial coefficients use bnc(n,k).
see also: bnc

ncol
m.ncol number of columns in matrix m
see also: nrow size

nextPerm
x.nextPerm reorders x to its lexicographically next permutation (active function)
e.g.
x=1:4; for i=1:(4!) x;; x.nextPerm; 
see also: prevPerm shuffle swap_row swap_col before

norm
norm(m) returns the Frobenius (or Euclidean) norm of m, that is, the sqrt of the sum of the squares of the elements. (For a vector this is the familiar "length"). For the normal distribution, see normal, gauss and err.
e.g.
norm(1,4,8)  # sqrt(1+16+64) = 9
norm(1:24)
see also: sumsq stdev gauss err normal

normal
The normal distribution function can be obtained using
Nor(x) := gauss(1/sqrt(2pi), x)
The normal distribution function with stdev sig is
Nor(sig, x) := gauss([1/(sig sqrt(2pi)),sig], x)
For the cumulative probability, use
erfc( x / rt2 )/2

e.g.
z=seq(-3,3); plot(z, [erfc(z/rt2)/2; gauss(1/sqrt(2pi),z)])
see also: gauss, err, erf

nrow
m.nrow number of rows in matrix m
see also: ncol size

ode
ode(dy, dfdy, a, y0, t)
dy(a,y) = function returning dy[i]/dt
dfdy(a,y) = function returning Jacobian
a = parameters
y0 = initial conditions
t = times at which to obtain y(t)
The function returns the values of y(t). Use ode carefully! If your functions return a vector or matrix of incorrect size, it may result in a crash.
e.g.
For example, for a set of two first-order equations in (y,v) we might have
dy/dt = v dv/dt = -g v - w y The Jacobian is then the set of values d(ydot)/dy = 0, d(ydot)/dv = 1 d(vdot)/dy = -w, d(vdot)/dv = -g For the case of explicit time-dependence, see >> # damped harmonic oscillator, a = [omega^2, gamma]: dy(a,y) := [y.2; -a . y] dfdy(a,y) := [0, 1; -a.1, -a.2] t = seq(0,10,100); y = ode(dy, dfdy, [4,1], [1;0], t); plot(t,y
# Van der Pol oscillator: dy(mu,y) := [y.2; -y.1 + mu*y.2*(1 - y.1^2)] dfdy(mu,y) := [0, 1; -1 - 2*mu*y.1*y.2, mu*(1 - y.1^2)] t = seq(0,100,101); y = ode(dy, dfdy, 10, [1;0], t); plot(t,y
see also: integ

Further information. The case of equations with explicit time-dependence is under development.

ones
ones is like zeros but returns a matrix of 1's.
see also: zeros

pause
pause(n) pause for n milliseconds
(only accurate up to system clock ticks)
pause(0) wait for next tick

see also: tic toc waitgetclick getclick click

plot
plot x, y for vector x,y plots y vs. x
plot m for (2 x n) matrix m plots 2nd row vs 1st row
or for (n x 2) matrix m plots 2nd col vs 1st col
plot x, m for matrix m plots the rows (or cols) of m vs. x
plot x1,y1,x2,y2, ... plot multiple lines (each can have a style string)
plot(func, min, max) plots func(x) between x=min and x=max
plot(expr; x, min, max) plots expr vs x
plot(expr; x, xvals) plot at given x points
plot('box', xywh, style) plot a rectangle
The return value is an id number (a handle) that can be used by replot.
Line Style
An optional final string parameter may be used to specify the line style. The style string can specify one or more of
[colour] [marker type] [marker size] [fill colour] [line type] [line width]
Example colours: r a y g b i v k w
Marker type: . + o s x t ~ | ! _
Line type: - = : ; full, dashed, dotted, dash-dot
Fill in: #
e.g.
x=0:0.01:2pi; plot(x,(x-4)^2);
plot(x,[sin x; cos x; tan x]);
plot(x, sin x,'-', x, cos x,'=');  # different styles
fix; plot(x, sin(x)/2,'b4');       # add another line
x=seq(-12,12,500); 
unfix; plot(x,(sin x/x)^2,'#b');   # fill in
#
plot(cos, 0, 2pi);          # a smooth curve
plot(cos, [0:6]);           # just a few points
plot(sin(x^2); x, 0,3);     # expression syntax
plot(cos x; x,0,2pi,'r=');  # dashed red line
see also: axis fix marker loglog replot figpos fill ellipse polyline errbar title

Further information. Plot style-string format
[^][colour][[marker][marker size]][line style][line width]
markers . + o x s t ~ ! | _
line style - = : ; solid, dashed, dotted, dash-dot
special ( , ellipse, multiline
A ^ at the start (optional) indicates the plot is being prepared for a replot. The colour code character must be next if it is present. The marker and line style characters can be anywhere. The marker size (if specified) must follow the marker, and the line width must be at the end. '+4' means a cross of size 4; '+ 4' means a cross drawn with linewidth 4.
Most letters correspond to a colour (apricot, blue, cream, ... etc.) See ?colour for a complete list. An upper case letter gives a brighter version of the same colour (so r is red, R is bright red).
e.g.

":"      dotted line
"r2"     a red line of width 2
"g="     green dashed line
"b+8"    blue crosses, marker size 8
"b+8 2"  blue crosses, marker size 8, pen width 2
"ko20-"  big black circles joinned by a thin line
"k. 8"   for dots the size is determined by the line width

Special line styles
(    is used for ellipses: see the ellipse function.
,    is used for polylines (not yet available).
see also: show_colours use_colour

poisson
poisson(mu,n) returns the Poisson distribution function
= exp(-mu) mu^n / n!
where mu (the mean) must be scalar but n (the random variable) can be vector or matrix. poisson(mu,n) gives the probability of n events occurring in a fixed interval of time or space if these events occur independently and with a constant mean rate.
e.g.
n=0:25; p = poisson(5,n); barchart(n,p);
see also: gauss binomial

Further information. poisson(mu,n) gives the probability of n events occurring in a fixed interval of time or space if these events occur independently of the time or location of the last event and with a constant mean rate. For example, a continuously illuminated gas will emit light by fluorescence. The probability of detecting n emitted photons during a time interval tau is poisson(R tau, n) where R is the average rate at which photons arrive at the detector. Suppose n is a Poisson-distributed random variable, then the mean value of n is mu, and the variance is equal to the mean.
e.g.

mu=5; n=0:ceil(10mu); p=poisson(mu,n);
sum(p n)        # mean
sum(p (n-mu)^2) # variance

poly
poly(a, x) returns the value of the polynomial
c_ + c_{1} x + c_{2} x^{2} + c_{3} x^{3} + ... + c_{n} x^{n}
where n = a.size - 1,
c_ = a[1], c_{1} = a[2], ... c_{n} = a[end]

see also: polyshow

polyshow
polyshow(cf) returns a string describing the polynomial given by coefficients cf.
e.g.
polyshow([2 3 0 -5 8])
see also: poly

pop
x.pop pops x. The last item is removed from x and returned. This is an active function.
y = x.pop is equivalent to y = x(end); x
see also: stack queue qpop push top clear

precision

see also: numeric_limits, str

prevPerm
x.prevPerm reorders x to its previous permutation (active function)
see also: nextPerm shuffle

prime
- For prime numbers,
see also: isprime primeFactors primeList

primeFactors
primeFactors(n) returns a list of prime factors of n.
To use primeFactors, first use isprime, and then ?primeFactors will give further information.
see also: isprime, primeFactors

primeList
primeList(n) returns a list of prime numbers up to n.
To use primeList, first use isprime.
see also: isprime, primeFactors

print
print filename creates an svg file of the current figure. The svg format can be read by most browsers, and various other programs. This function is at a rather preliminary stage which results in limited resolution. At the moment it uses the on-screen figure dimensions as those of the printed figure. Text output remains basic (does not yet offer colouring or bold/italic/underline). If you want publication-quality output, use texplot.
e.g.
plot(gauss(1,x)/sqrt(2pi); x,-4,4); xlabel('x'); print 'myfig';
see also: plot texplot

prod
prod(x) the product of the elements of x.
prod(f, n, x) the product of f(n_i, x)
see also: sum

push
x.push(item) push item onto the end of x.
An item is a row of a matrix or an item in a list.
This is an active function: it is equivalent to x ;= item.
see also: stack queue pop top clear

property
property('property_name', 'substance_name') Looks up an item in the database. The '<<' symbol is also allowed as a shorthand for property lookup (see the examples below). You can use the * ('wildcard') symbol to indicate an abbreviation, e.g. "zir*" means anything beginning with "zir". The examples illustrate the most common cases.
The database mostly gives physical properties, but it also includes a list of formulae. This function is slow: you should typically look up a property only once and store the result. To make the function "silent" (i.e. no displayed information) supply a second output argument.
e.g.
<< radius of Earth                 # find out the radius of Earth
r << radius of Earth               # store it
<< radius Earth                    # you can miss out the "of"
m << mass carbon                   # further examples
d << density of copper             # 
[m, info] = property('mass','H');  # silent running
<< gallon convert                  # convert to SI units
<< gallon in si_unit               # same thing
m << mass zir*                     # use of *
m << mass 'planet mercury';        # the planet not the element
<< formula cosine
<< formula Coriolis
# To find the resistivity of copper at 50 degrees celcius:
rhoT << resistivity of copper; rho = interp(rhoT, T0+50)
#
<< * H                             # list all properties of H
<< radius *                        # list everything having a radius property
for i=1:10; property('boiling',i);

Further information.

qfind
For an orderered list x,
qfind(x,v) returns index of the first element >= v.
If all the elements are below v then qfind returns (n+1) where n is the number of elements in x.
This uses a fast search (O(log n)).
e.g.
# find approximately where x = cos(x)
x=seq(0,2,1e5); y=x-cos x; tic; k=qfind(y,0); toc  # quicker than find(y >= 0)
see also: find fzero

qinteg
qinteg is like integ but it is faster.
The integ function performs better with singularies, and can handled infinite intervals. If you use qinteg with an infinite integral then in fact integ will be invoked.
Another fast integration method is provided by binteg. The main difference is that for qinteg you specify the function, while for binteg you provide a large number of equispaced values of the function. qinteg uses an adaptive method.
see also: integ binteg

Further information. ---acknowledgement--- Parameter values for Gauss-Legendre integration were obtained from
https://pomax.github.io/bezierinfo/legendre-gauss.html

qpop
pop a queue. That is, remove the first row and return it.
see also: pop push queue

bessel
Bessel functions
syntax: besselj0(x), besselj1(x), besselj(n,x)

see also: besselj0 besselj1 besselj

Bessel
Bessel functions
syntax: besselj0(x), besselj1(x), besselj(n,x)

see also: besselj0 besselj1 besselj

besselj0
besselj0(x) returns the Bessel function J{_0}(x).
e.g.
plot(besselj0, 0, 20)
see also: besselj1 besselj airy

besselj1
besselj1(x) returns the Bessel function J{_1}(x).
e.g.
plot(besselj1, 0, 20)
see also: besselj0 besselj airy

besselj
besselj(n,x) returns the Bessel function J{_n}(x).
e.g.
plot(besselj(3,x); x,0,20)
see also: besselj0 besselj1 airy

binteg
binteg does integration using a simple method.
For a vector y containing the integrand evaluated at equispaced x values:
binteg(y) estimates the integral by 5th order interpolation.
binteg(y) dx where dx is the x spacing gives the answer
For integration with more features, see integ.
e.g.
# area under a Gaussian curve. Answer should be sqrt(pi)
x=seq(-6,6); dx=x.2-x.1; binteg(exp(-x^2)) dx
see also: integ

Further information. binteg uses Boole's 5-point rule. It works for well-behaved functions. It does not handle singularities (e.g. a function going to infinity). binteg is quick when the function can be evaluated rapidly on a vector of x values. If your function requires a lot of work for each value, or the region of integration is wide, then integ will be faster.

qload
qload is used for quick loading from disk, in binary format.
m = qload(filename)
or after "qsave m" use "m = qload m";
see also: qsave load

qsave
qsave is used for quick saving to disk, in binary format.
qsave(filename,m) saves matrix m to a file of the given name.
qsave m (TBC) is a shorthand intended for use with global variables (e.g. from the command prompt). Here 'm' is both the file name and the name of the variable to be saved. The result is to save matrix m to a file called 'm.jmt'
qsave filename name can also be used.
see also: qload save

queue
You can use a matrix as a queue via the functions push and qpop.
see also: push qpop isempty stack end

rand
rand(n) returns a list of n random numbers between 0 and 1
rand(nr,nc) returns a (nr x nc) matrix
e.g.
x=rand(500); y=rand(500); plot(x,y,'.');
see also: irand rnd err randseed

randexp
randexp(G,n) returns n random numbers drawn from an exponential distribution with mean 1/G.
e.g.
x=randexp(1,1000); h = x.hist; histplot h
see also: rand err

randperm

see also: shuffle

randseed
randseed(i) re-seeds the random number generator, where i is an integer.

range
range(x) returns the range of x, i.e. (x.max - x.min)

rat
rat(x) returns a rational approximation to each element of x
rat(x,1) for scalar x returns the continued fraction expansion of x,
e.g.
rat(9/13)                      # returns [9;13]
x = [2/5, 9/13, 3/4]; rat(x)   # returns [2 9 3; 5 13 4]
a=rat(13/29,1)                 # returns a = [0,2,4,3] because 
                               # 13/29 = 0+1//2+1//4+1//3
a.1 +1//a.2 +1//a.3 +1//a.4    # this evaluates to 13/29
rat(exp(1),1)                  # try it!
rat(sqrt(2),1)
see also: contfrac round whatis

readcsv
readcsv [m, headings, mtitle, info, strlist] = readcsv(filename)
[m, headings, mtitle, info, strlist] = readcsv(filename, nonnum)
[m, headings, mtitle, info, strlist] = readcsv(filename, nonnum, len) Read a csv (comma-separated value) file.
filename is the file name,
nonnum (default value 0) is explained below,
len indicates how many characters you want to retain from the column headings.
The default value is the length of the longest heading.
This function returns the data in a numerical array m. It is intended for use with, for example, a spreadsheet. If the first line of the file looks like a title, then it is placed in mtitle. Otherwise mtitle is set equal to the file name. If the first line, or the one after the title line, contains any non-numerical entries (e.g. strings) then it is taken to be a list of column headings.
After that, numerical values are read, and non-numerical items (e.g. strings and blanks) are given the value nonnum. This nonnum defaults to zero but you could consider using -1 or nan, for example.
info can be used to obtained some counts:
info = [n_blank, n_zero, n_str, n_other]
n_blank = number of blank items (strings of zero length)
n_zero = number of numeric items with the value 0
n_str = number of string items
n_other = the rest, i.e. non-zero numeric values
strlist returns a list of all the string entries in the table, in the format '[row,col]"entry" [row,col]"entry" ... etc.'
see also: readcsvs load readtext savecsv

readtext
readtext(filename) reads a complete text file, returning the contents as a list of strings.
see also: fread writetext load

regularize
[xr, yr] = regularize(x,y) returns an ordered equispaced set of x values and corresponding y values obtained by linear interpolation from irregular data x,y.
e.g.
x=irand(20,20); y=9sin(x)+err(20); plot(x,y,'o-');
[xr,yr]=regularize(x,y); plot(x,y,'o',xr,yr,'+-');
see also: smooth

Further information. Method: x is first sorted, then at repeated x points the mean value of y is taken, then a sequence from x.min to x.max is created for xr, and yr = interp([x,y],xr).
The step size in the sequence is taken as the smallest step size in the x data if a substantial proportion of the data has that spacing, or if the average spacing is not much larger. Otherwise a step half way mean the smallest and the average step is used. However, we don't allow xr to be more than 1000 times larger than x.

replot
replot is used either to tidy up the current figure, or for animation
replot re-draws the whole of the current figure
replot() ditto
replot(id) re-draws subplot number id
(e.g. use this to tidy up after changing a text)
replot(y) re-plots the most recent curve using new y-values
replot(x,y) re-plots using new x and y values (must be non-scalar)
replot(id,y) or replot(id,x,y) re-plots curve number id, where
id is the id number furnished by the plot command.
replot(id,0) turns off (i.e. makes invisible) item id
replot(id,1) turns on (makes visible) item id
replot(id, str) change the style of a curve or the text of a label
replot(id, 'style', str) change the style of a text label
replot is fast, intended for use in animations. When using replot repeatedly you may need to call getmouse or update as well, to force Windows to keep updating the figure.
e.g.
x=seq(0,2pi,100); plot(cos(2x), sin(3x), 'r')
for n=1:200 replot(cos(2x-2*Toc), sin(3x)); wait(20); 
#
x=seq(0,2pi,50); plot(cos(x), sin(x), 'o15');
for n=1:200 replot(cos(x), sin(x-3*Toc)); wait(20); 
see also: plot demo replot_move

Further information. To replot a curve consisting of a single point you have to use replot(id,x,y).
When using replot to change colours, you can cause mistaken pixels when items move around and intersect, unless you use the '^' control character consistently.
e.g.

test := unfix; p=plot([0 3],[0 3],'g3'); fix; return p; 
p=test; q=plot(1,1,'^b. 20'); replot(q,'^r. 20'); replot(q,1,2) # ok
p=test; q=plot(1,1,'b. 20'); replot(q,'r. 20'); replot(q,1,2)   # no
p=test; q=plot(1,1,'^b. 20'); replot(q,'r. 20'); replot(q,1,2)  # no

replot_move
replot_move(p, dxy) moves plotted items p by dxy = [dx, dy] and returns the new [x,y]
e.g.
p=0; p.1=fill([0 4 2],[0 0 2],'G');fix; p.2=plot(2,2,'o20'); axis(0,9,0,9)
for i=1:200; replot_move(p, [2 1]/100); wait(10); 


rescale
rescale(f,xysc, x) gives a re-scaled version of a function f.
It returns
y0 + ys * f( (x-x0)*xs ) where xysc=[x0, xs, y0, xs]
rescale(f,par, x) with size(par) > 4 gives a re-scaled version of f(a,x), in which a=par(5:end) This may be useful in combination with lsfit, see further information.
e.g.
tt=-9:9; y=rescale(sin,[1 0.2 3 4],tt); plot(tt,y)

Further information. The calibration of experimental equipment is often obtained by curve fitting. Suppose your experimental signal is expected to have the form y=f(a,x) for some function f known to you, but the equipment has unknown x and y offsets and scale factors. Then you might want to fit the data to the function
y0 + ys * f( a, (x-x0)*xs )
with both the parameters a and also the scale information (x0,xs,y0,ys) to be extracted from the best fit. You can achieve this by adapting your function f, but since it is a fairly common process, the use of rescale offers a convenient shorthand. For example, you could define a user function as follows
rf(p,x) := rescale(f, p, x) Here the first 4 elements of p are used for the scaling information, and the rest are passed to the function f. You would then use
lsfit(rf, p0, xdata, ydata)
where p0 is an initial guess of both the scaling and other parameters.
e.g.

f(a,x) := exp(-a x) cos(x)
rf(p,x) := rescale(f, p, x)
x=0:20; y = 20 f(0.1, 0.8x) + err(21)
lsfit(rf, 1:5, x, y)

reshape
reshape(m, dims) returns a matrix m reshaped to the given shape.
dims is typically a vector of two components, as in reshape(m,[2,3]). The reshape is only carried out if it preserves the number of elements.
If dims is a scalar then we form the square matrix, see examples:
e.g.
m=1:16; reshape(m,[2,8]);; '--';; reshape(m,4)
see also: size, nrow

reverse
reverse(v)
Returns the vector (or matrix) with elements in reverse order.

rfind
rfind(x) returns the index of the last non-zero element of x, or zero if none are found.
see also: find findall

rnd
rnd returns a single random number in the range 0 to 1
e.g.
x = rnd
see also: rand irand err

round
round(x) round to nearest integer
see also: floor ceiling

rowsums
m.rowsums returns the vector of row sums of matrix m
see also: sum colsums

save
save is used to save an ordinary matrix (not a list) to a text file. You can also set the precision, and specify a header. This is intended for rapid storage of data in matrix form. For more general file handling, use fwrite.
save(filename, m) save a single matrix
save(filename, m, header) save first the header, then m
A final scalar argument is interpreted as the required precision. For example
save('myfile.txt', m, 3) will record m to 3 significant figures.

see also: load savecsv dispfile fwrite writetext

savecsv
savecsv(filenm, m)
savecsv(filenm, m, headings)
savecsv(filenm, m, headings, title)
save matrix m to a csv (comma-separated value) file.
headings, if provided, is treated as column headings. It should be an array of strings (i.e. each row is a string), padded with spaces where necessary. Trimmed versions will be writtem to the file.
If title is provided then it is written to the first line of the file. Returns the number of rows of m.
see also: readcsv

seq
seq(start, end, num) returns an evenly spaced sequence of num values between start and end.
e.g.
x = seq(0,10,100); plot(x, cos x, 'o');

setminus
a.setminus(b) returns the set difference a-b (i.e. members of a not in b)
see also: intersect setxor union

setmouse
setmouse(info) stores info in mouse. It can be retrieved using getmouse.
e.g.
setmouse('hello'); disp('retrieved ', getmouse('m'));
setmouse(pi); disp( 'retrieved ', getmouse('m') );
see also: getmouse onLDown

setxor
a.setxor(b) returns the set symmetric difference (i.e. members of (a union b) not in (a intersect b))
e.g.
a = 1:5; b = 3:6; a.setxor(b)
see also: intersect setminus union

SGfilter
SGfilter(nl,nr,m) returns coefficients for a digital filter
nl = number of points to left of (before) given point
nr = number to right
m = order of the polynomial
SGfilter(n) 2nd-order symmetric filter over n points
(i.e. nl=nr=floor(n/2))
SGfilter(n,m) m'th order symmetric filter
SGfilter(nl,nr,m,d) returns coefficients for d'th derivative
see also: smooth

Further information. The digital filter is a Savitzky-Golay filter. When data is convolved with the filter, the effect is to fit a polynomial of order m to the points (j-nl ... j+nr) and then replace the point j by the value of the fit at the that point. Therefore m=0 gives no change, m=1 is a runnning average, etc. Low m tends to flatten and broaden peaks.
The coefficients are returned in "wrap-around" order. e.g. for 5 points the coefficients abcde would be returned in the order cbaed.

shape
m.shape returns a row vector giving the sizes of the dimensions of matrix m
see also: size nrol ncol

shift_round
x.shift_round(n) x=1:10;; x.shiftround(3); x
see also: shuffle swap_col swap_row reverse

show_colours
Displays a figure illustrating the available colour codes.
see also: useColour plot wipe

shuffle
shuffle (x) returns x randomly re-ordered.
shuffles the items in a vector or a list, or the COLUMNS of a matrix
see also: reverse irand next_perm shift_round

sign
sign(x) sign of x = (-1,0,1) for (x<0, x=0, x>0)
see also: abs fstep tophat

sin
sin(x) returns the sine of x.
see also: cos tan asin sinh sinc

sinc
sinc(x) returns sin(x)/x
see also: sin

sinh
sin(x) returns the hyperbolic sine of x = (exp(x)-exp(-x))/2.
see also: cosh tanh

size
For any symbol a, a.size returns the number of elements.
see also: sum mean nrow ncol

slf
slf(x,y) or {*slf(x,y,dy)} straight line fit. This fits the line y = a + b x
to data (x,y). The routine returns a matrix [a, siga; b, sigb; chi^2, Q] where a,b are the best fit parameter values, siga, sigb their uncertainties (1 standard deviation), and see ??slf for the rest. The routine also counts outlying points and displays a remark. If you specify a second output parameter, as in
[p, info] = slf(x,y)
then chi^2 and Q are returned in info.
For silent running (i.e. no plot), provide a further input parameter of string type (see third example below).
e.g.
x=1:20; y=2+7x+err(2, x.size); slf(x,y, 2)
[p,info] = slf(x,y,1,'');   # no plot
see also: lsfit errfit chisq

Further information. If you use slf(x,y,dy) then dy (the experimental uncertainties on the y data) is either a vector the same size as y, or a scalar if all points have the same error. If you do not supply dy, an attempt is made to estimate it from the data by looking at groups of 10 points at a time and finding their rms departure from a straight line.
Let chisq = sum (data-fit)^2 /dy^2
Q is the probability that chisq could exceed the observed value by chance, under the standard assumptions of least-squares fitting (see chisq for more information). It is given by
Q = gammaQ(nu/2, chisq/2)
where nu is the number of degrees of freedom, here equal to n-2 for n data points. To explore the meaning of this parameter, try the following:
e.g.

x=1:20; y=x+err(x.size); slf(x,y,1)  # Q is about 0.5
slf(x,y,0.6)  # errors underestimated: Q is small
slf(x,y,2)    # errors overestimated: Q is suspiciously close to 1

smooth
smooth(a, y) applies smoothing to data y using a filter defined by a
It is assumed the data has been sampled on an equispaced grid. The coefficients in a are as for SGfilter.
e.g.
x=seq(0,3.1,200); y=5sin(x^3) + err(1,x.size);
plot(x,y,'g',x,smooth(y),'b2');
plot(x,y,'g',x,smooth([25,4],y),'b2');
see also: SGfilter convolve regularize

Further information. The Savitzy-Golay filter of even order m is equivalent (for purposes of smoothing) to one of order m+1. Therefore you typically pick order 0, 2, or 4. Order 0 gives a running average.

snipImage
snipImage creates a new bitmap from part or all of an existing one. It can be used, for example, to copy a bitmap, to create a thumbnail, or to select a rectangular region. It returns the id of the newly created bitmap. snipImage(id, [x,y,w,h]) get the part indicated
snipImage(id, [x,y,w,h], ht) get part and resize to given height
snipImage(id, [x,y,w,h], [wd,ht]) resize to given width and height
snipImage(id, ht) make a copy with height ht, maintaining aspect ratio
snipImage(id, [wd,ht]) make a copy with given width, height
see also: loadBitmap

solve
solve(m,b) returns a vector x such that m.x = b
where m is a square matrix and b is a column vector.
Mathmatically, this is equivalent to x = inv(m).b but numerically the solve function is faster and more accurate.
solve(m,bb) where bb is a matrix solves for a set of column vectors (equivalent to but more precise than inv(m).bb).
If you want to use the same matrix again with a different vector b, then you can save time by using
solve('',b) where the first parameter '' means "use the same matrix again". Similarly, you can get the inverse and determinant of m using inv('') and det('').
e.g.
m=[17,89,71;113,59,5;47,29,101]
b=[408;246;408]; x=solve(m,b)         # the answer is [1;2;3]
m.x
see also: LUform inv det

sort
sort(x) returns a sorted version of x (lowest member first).
sort(m,c) returns matrix m with the rows sorted by the values in column c. This is a passive function. If you don't need to keep the unsorted version and want a slight gain in speed, use sortit. To get the indices, use sortind.
e.g.
x=[2 1 4 5 7 5]; sort(x)       # returns 1 2 4 5 5 7
see also: sortit sortind sortrows unique reverse

sortind
sortind(x) returns the indices of sorted x, without changing x
e.g.
x = irand(50,[1,20]); i = x.sortind; [x; i; x.i]
see also: sort sortit active

sortit
x.sortit sorts x in place (and returns the size of x). This is an active function.
e.g.
x=[2 1 4 5 7 5]; x.sortit       # returns 6, and x is now 1 2 4 5 5 7
see also: sort sortind sortrows reverse active

sortrows
m.sortrows sorts the rows of m and returns the indices.
This is an active function.
e.g.
m=irand(10,[8,4]); mm=m; ind = m.sortrows
see also: sort sortind sortit active uniquerows

split
split(s) returns a list of the words in string s
split(s, c) returns a list of the parts of s separated by c
split(s, c, q) returns a list of the parts of s separated by c,
but parts bracketed by q are kept together
e.g.
w = split('all the pretty horses')
w = split('this one; that one', ';')
w = split('1, 2, "Name, firstname", 3', ',', '"')
see also: join list trim

sqrt
sqrt(x) square root of x

stack
- A column vector or a matrix can be used as a stack via the functions push, top, pop. These methods are useful for small stacks but not efficient for large ones. A more efficient stack type is planned but not yet available.
see also: push pop top queue

stdev
a.stdev gives the standard deviation of the elements of a
see also: mean size variance

step
For the step function, use fstep
see also: sign fstep tophat

str
str(x, n) returns a string version of the number x up to n significant figures.
str(x) gives x to 6 significant figures.
e.g.
s = ['pi=', str(pi)]     # Not s = ['pi=', pi]
see also: str2num

Further information. To find the character having a given ascii integer code such as 110, use
s = '', 110
This means "construct a string, starting with empty string, then character number 110".

list2str
list2str(s) converts a list of strings into a string array.
e.g.
strlist( list('hi','there','bud') )
see also: list str2num

str2num
str2num(s) converts a string such as '2.5' to the number 2.5
e.g.
str2num('2.5') 
see also: isnum str

Further information. To find the ascii integer codes for a string such as 'hello', use
a = 0+'hello' This means "add zero to 'hello', and interpret the result as a number".

strfind
strfind(a,b) or a.strfind(b) finds the first occurence of b in a, where b can be a vector
findstr(a,b) is a synonym.
If a is a matrix, then the function looks for b in each row, and returns a column vector.
e.g.
strfind([2 7 1 8 2 8 1 8 2 8 4 5 9], [8 4])
strfind("You can't fool all the people all the time", 'all')
strfind(['welland';'landed ';'nothing'],'and')
see also: find strfind_last ===

strfind_last
strfind_last(a,b) or a.strfind_last(b) finds the last occurence of b in a, where b can be a vector
e.g.
strfind_last([2 7 1 8 2 8 1 8 2 8 4 5 9], [8 2])
strfind_last("You can't fool all the people all the time", 'all')
see also: find rfind strfind ===

subplot
subplot is used to specify multiple plotting areas on the same figure.
A call to subplot picks a given subplot, creating it if necessary.
The most common usage would be subplot(i,n) or subplot(nr,rc,i).
subplot(i,n) the i'th of n in total.
subplot(nr,nc,i) the i'th from an array of (nr x nc) subplots.
id = subplot(x1,x2,y1,y2) new subplot at the specified coordinates.
The coordinates used are relative to the window area, with the range 0 to 1.
subplot(id) pick an existing subplot (scalar id)
subplot(x1,x2,y1,y2, id) move a subplot.

e.g.
for j=1:6; subplot(j,6); plot(sin(j x);x,0,2pi); 
subplot(0.3,0.6,0.2,0.4); plot(exp x; x,-1,2);
see also: plot fix wipe

Further information. subplot has a flexible syntax:
e.g.

subplot([i,n])              # same as subplot(i,n) 
nrc=[2 3]; subplot(nrc, i)  # same as subplot(2,3,i)
rect=[0 0.5 0.2 0.6]; subplot(rect)
subplot(rect, i)            

sum
sum is used to sum elements of arrays, or sequences of function values and things like that.
x.sum returns the element sum of a vector, or the column sums of a matrix.
A difficulty may arise when x is a matrix with a single row. Then x.sum will return the sum of that row. To be sure of getting the column sums, use colsums.
For summing function values, you can do things like:
sum(func, n, x) the sum (over i) of f(n_i, x)
sum(func, n1, n2) the sum of f(n) for n in the range n1 to n2 (both scalar)
sum(expr; n,vals) sum an expression for values of n in vals.
sum(expr; n,n1,n2)
e.g.
f(n,x) := (n mod 2) sin(n x)/n        # Fourier component for a square wave
x = seq(0,4pi,500);
y = sum(f(n,x); n, 1:20); 
plot(x,y);
y = sum(sin(n x)/n; n,[1:2:20])       # another way to do it
see also: mean stdev size colsums rowsums

sumsq
x.sumsq returns the sum of the squares of the elements of x.

e.g.
sumsq([3, 4])
see also: sum variance

swaprows
m.swaprows([a;b]) swap rows
a and b can be a pair of scalars or two row vectors. The swaps are done in order. active function
see also: next_perm shuffle active

table
y = table(f, x) construct the vector whose i'th element is f(x.i) (useful if the function only accepts scalar input).
y = table(f,n,x) construct a table whose i'th row is f(n_i, x) If subsequent rows are shorter than the first, they will be padded with zeros. If they are longer than the first, an error is generated.
e.g.
table(bnc, 1:6, 0:10)              # table of binomial coefficients
table( integ(x^n; x, [0,1]); n,0,4 )  # table of integrals
x = seq(0,pi,7); table( sin(k x); k, 0, 3)
see also: eval sum vectorize

tan
tan(x) returns the tangent of x.
see also: sin cos atan tanh.

tanh
tanh(x) returns the hyperbolic tangent of x = sinh(x)/cosh(x)
see also: sinh cosh tan.

tex
TeX, LaTeX and Calqit To generate a figure suitable for loading into a LaTeX file employing Tikz graphics, see texplot. To generate a table use {=textable}. To write mathematical expressions to display on screen, Calqit provides a succinct TeX-like formatting language which is summarized in the further information.
e.g.
disp '
p G w'; # Greek letters formed by p G disp 'x^{2 m_{1,2}'; # superscript, subscript: the braces are required disp 'leq sqt inf < >
see also: texplot textable

text
text(x,y, label) add a text label to the plot.
You can also use:
text(x,y,string,style)
text(placement, x,y,string,style)
text(xy,string) # xy has two components
A text with exactly the same x,y as an existing text will replace it. You can also change the text or style using replot.
The placement is a string, one of: n,ne,e,se,s,sw,w,ne
To move an existing text, use replot or replot_move. Another way to place a label is to use subplot and title.
e.g.
axis([0 100 0 100]); text(40,60,'Hello');
text('sw', 40,60,'sw of point, red', 'r');
text(20,20,'2
pi+e
see also: replot title xlabel createButton

Further information. The format is
text(x,y, yourtext, [colour/size/font])
The colour and size is specified by a string such as 'b14', where the first character is a colour code, and the number gives the size. One of the following characters can be used to indicate the font:
* bold
= underline
/ italic
. normal
^ superscript
_ subscript
$ symbol
e.g.
axis(0,100,0,100); text(20,60, 'bold font', '*');
text(20,40, 'green italic font', 'g/');
You can change font within a given text by inserting control characters. For example
A text such as
"I have normal font and {* bold font and {/ italic font}", '20')
displays as
"I have normal font and bold font and {/ italic font}"
If you omit the closing brace \}, it means the font or colour extends to the end of the current line.

see also: plot title subplot

texplot
texplot generates a LaTeX file suitable for generating figures using the tikz package. The general syntax is
texplot(x,y,filename,[xyrange],[style],[xlabel],[ylabel],[axisstr])
e.g.
texplot(x,y,'myplot')
texplot(x,y,'myplot',[-3,3]) # x range
texplot(x,y,'myplot',[-3,3,1,5]) # x and y range
# Example including x and y axis labels:
texplot(x,y,'myplot',[-3,3,1,5], [], '$r,$(m)', '$f,$(N)')
texplot(x,y,'myplot','addplot') # add to an existing file
The style parameter is used to furnish line styles in a semicolon-seperated string, one style for each line. e.g. if there are two rows in y then you could use
texplot(x,y,'myplot',[-3,3],'blue;dashed')
The axis labels are latex strings.
axisstr may be used to put in further info such as tick positions.
For logarithmic plots, add information to the file name string, as in:
texplot(x,y,'myplot; loglog')
texplot(x,y,'myplot; semilogx')
etc.
For multiple lines on the same graph all with the same x, use a matrix y, with each row corresponding to one plotted line. For several lines with different x, use matrices for both x and y. To add labels within the plot use the form texplot(x,y,filename,[xyrange],'label',s) where x,y gives the location(s) and s is a string matrix with one row for each label e.g. texplot([1 2],[3 4],'myplot','addplot','label',['$x=1$';'$y=4$'])
e.g.
x=seq(0,2pi,50); texplot(x,cos(x),'myplot')
x=seq(1,5,20); texplot(x,gamma(x),'myplot',[0,5],'','$x$','$
dispfile 'myplot.tex'
see also: print plot

textable
textable(m) returns a string array suitable to display a table in LaTeX. textable(m, h) provide column headers (a string array)
textable(m, h, rh) provide column and row headers
textable(m, N) specify precision

see also: texplot tex

tic
tic restarts the timer, toc displays the elapsed time in milliseconds, Toc displays the elapsed time in seconds.
e.g.
tic; a=1:1000; a.shuffle; a.sortit; toc
see also: toc pause oclock

time

see also: tic toc oclock today

title
title(string) add a title to the plot
title(string, style)
e.g.
plot( [0 1 2], [0 1 0] ); title 'My graph'
see also: plot text xlabel ylabel

toc
toc gives the elapsed time in milliseconds, Toc gives it in seconds.
see also: tic pause.

Toc
Toc (with capital T) gives the elapsed time in s, toc gives it in milliseconds.
see also: tic pause.

today
Returns today's date as a string, in the format 'ddd mmm nn yyyy', for example 'Mon Aug 12'
see also: oclock

top
x.top returns the last row of a matrix. This allows one to use a matrix as a stack, in conjuction with push and pop. Note, for a column vector x.top and x.end are the same, but for a row vector they are not the same.
see also: pop stack queue end

tophat
tophat(x) the `top hat' function = zero everywhere except in the interval 0 <= x <= 1. Equal to 1 inside this interval and to 0.5 at x=0 and x=1.
see also: sign step

trace
trace(m) returns the trace of m, i.e. the sum of the main diagonal
see also: det

trim
trim(s) trims leading and trailing spaces from a string, or leading and trailing zeros from a numeric vector. Also converts numeric values to integers.
e.g.
s = '  hi there '; t = trim(s); ['>',t,'<']
see also: split pad

true
boolean TRUE

type
type(x) returns the type of variable x.
To find out about types of variable, use ?types.
(To display a file, use dispfile).

see also: types isdefined ischar isboolean dispfile

unfix
Turns off `fix' for plotting. After a call to unfix, a subsequent plot command will delete the current graph and start a fresh one. You can also use unfix to create an empty figure window.
e.g.
unfix; plot((x-2)^2; x,0,4);
see also: fix wipe plot subplot

union
union(x,y) returns the set union of ordered sets x and y.
e.g.
x=[1 2 3]; y=[1 3 4 5]; union(x,y)   # returns 1 2 3 4 5
see also: sort intersect unique

unique
unique(v) returns the members of v, in an ordered list, with only one copy of any repeated members. v need not be itself sorted, but if you know that it is then you can obtain a slight speed-up by supplying a second parameter, as in "unique(v, 1)".
e.g.
v=[1 4 2 5 2 1 6]; unique(v)   # returns 1 2 4 5 6
see also: union issubset uniquerows

uniquerows
[mu, im, ic] = uniquerows(m) returns the rows of m with duplicates removed. If at the call, the matrix m has r rows with k <= r different forms, then
im is a list of k numbers, each in the range 1 to r,
giving the index in m of an example of each item in mu
ic is a list of r numbers, each in the range 1 to k,
giving the 'colour' of each row of the input matrix a thus mu = aim
and m can be reconstructed from mu
e.g.
r1=[0 1 1 2 2]; r2=[1 0 0 0 2]; r3=[1 2 1 0 0]; m=[r1;r3;r2;r1;r3;r3]
[mu, im, ic] = uniquerows(m)
see also: unique sortrows

update
update updates the current figure window. This forces all plotting to be completed and mouse status information to be retrieved. This can be necessary during animation, for example. It is not necessary however if getmouse has recently been called.
update is faster than replot(), because it does not repaint the whole figure.
see also: replot getmouse

useColour
useColour(rgb), where rgb is a vector of three integers, sets colour character 'u' to the given RGB colour and returns 'u'. If you supply a fourth number in rgb then it sets the colour code 'U' and returns 'U'. The rgb code is a set of three integers in the range 0 to 255.
e.g.
useColour([10 100 100]); plot(sinc,-3pi,3pi,'#u');
eg(r) := useColour([r,0,0])
axis([0 255 0 1]); for r=0:255; fill(r+[0 1 1 0],[0 0 1 1], eg(r));
see also: colour show_colours plot wipe fill

Further information. RGB colours are set by a triplet of integers in the range 0 to 255, indicating the amount of red, green and blue in the colour. For example, bright red is [255,0,0], yellow is [170,150,0], white is [255,255,255] and black in [0,0,0]. RGB colours include most colours that computer monitors can display and that human visual perception can distinguish.

variance
variance(x) gives the variance, i.e. sum of (x - x.mean)^2 divided by size(x)
see also: stdev mean sumsq

vectorize
vectorized simple functions. The syntax either
f(x) ::= ...
f(a,x) ::= ...
will cause the body of the function f to be evaluated separately for each element in x. This is useful when you have an expression which only makes sense for scalar x, but you want to evaluate it for many values of x.
e.g.
S(x) ::= integ( sin(t^2); t, [0,x] )  # Fresnel S function
plot(S, 0, 5);
see also: function table

wait
wait(t) waits for the internal clock to reach the next increment in steps of t ms. This is often more useful than the pause function.
see also: pause tic toc

whatis
whatis(x) returns a string which evaluates to x, to good approximation
whatis(x, tol) sets the tolerance (default 1e-9)
e.g.
whatis(3.141592653)
whatis( sin(pi/3) )
whatis( integ(gauss, [0,inf]) )
see also: rat eval contfrac

wipe
wipe(c) erase all plots and paint the figure with colour c
wipe([]) ditto, use existing background colour
wipe(i,c) reset the i'th subplot and paint its region
e.g.
for j=1:3; ubplot(j,3); plot(cos(j x);x,0,pi);
wipe(2,'w'); subplot(2); fix; plot(lor(1,x-1);x,0,2,'b2');
wipe('k');
see also: subplot fix plot figpos show_colours use_colour

writetext
writetext(filename, text) writes a value to a text file.
The value would usually be a list of strings or a matrix of strings, but it could be anything.
see also: readtext save fwrite

xlabel
xlabel('text') adds a label to the x axis of the current graph.
xlabel('text', style) to set size, colour etc.
see also: ylabel title

ylabel
ylabel('text') adds a label to the y axis of the current graph.
ylabel('text', style) to set size, colour etc.
see also: xlabel title

zeros
zeros(n) returns an (n x n) matrix of zeros.
zeros(r,c) or zeros([r,c]) returns an (r x c) matrix of zeros
see also: ones diag eye rand pad

zeta
zeta(s) returns the Riemann zeta function.
see also: gamma

syntax
calqit example statements (either type them in, or, more conveniently, double-click on any given line in order to execute it):
e.g.
pi                 # display the value of pi
r = 2              # set r equal to 2 
y = pi r^2         # set y equal to pi*r*r
bnc(4,2)           # call the function 'bnc' with arguments 4 and 2
s = 4:8            # set s equal to the sequence 4,5,6,7,8
s.3                # the third element of s
12 / s - 3         # divide has precedence here
12 // s - 3        # double / means divide by everything to the right
t=0.3; cs=cos t; sn=sin t;  # multiple statements
R=[cs,-sn;sn,cs]   # a matrix
R
R
v=[1,2]' # ' means transpose R . v # matrix multiplication x = seq(0,6pi,50); # a sequence of 50 values from 0 to 6*pi ?plot # get help on the plot function plot(x,sin(x)) # plot sin(x) verses x plot(sin(x); x,0,6 pi) # another way of doing it ?vars # gives a list of user variable names ?if # gives help on the 'if' clause syntax ??if # gives a list of keywords For functions taking one parameter, the standard syntax is f(x) where x is an expression. However you can omit the bracket in simple cases, such as sin x. (e.g. 'sin pi').
For several parameters, use f(x,y,z).
For more extensive help, see
https://users.physics.ox.ac.uk/~Steane/calqit/calqit_doc.htm

airy
airy(x) returns the Airy function Ai(x)
The precision can be set by a prior call to
set('airy', precision)
Also, set('airy')
will set the precision to the default value, which is 10-9 (and the calculated value will typically be better than this for small x).
Ai(x) = (1/p) int0{^
e.g.
plot(airy, -15,5)
set('airy', 1e-12); airy(1)
see also: bessel

arcosh

see also: acosh

arsinh

see also: asinh

artanh

see also: atanh

chisq
It is defined by
c2 = sum{_i}{(y{_i} - fit[va,x{_i}])/s{_i}}{^2}
where and fit[If the residuals are randomly distributed, and if that distribution is the normal distribution, and if you have estimated its standard deviation correctly, and if the model depends linearly on the parameters in the region explored by the data errors, then to have a mean n and standard deviation sqt(2n), where
n = n - m
is the number of degrees of freedom (n is the number of data points, m the number of fitted parameters).
The Q statistic is the probability that the assumptions mentioned above. It is given by
Q = gammaQ(nu/2, chisq/2)
Outliers in the data tend to make Q small, without affecting the fitted parameters much, and for this reason small values of Q (down to 0.001, say) are often deemed acceptable. Very small Q implies either your model is wrong or non-linear or your data errors are larger than you think, or they are significantly non-normally distributed.
see also: lsfit slf gammaQ

colsums
m.colsums returns the vector of column sums of matrix m
see also: sum rowsums

complex
complex(x,y) returns the complex number x + i y

see also: real imag conj abs arg argand

Further information. Complex numbers To introduce a complex number, use either the function complex or one of the built-in symbols 0i, 1i, 0j, 1j. For example
z = complex(2,1)
z = 2 + 1i
z = 3 + 0i If you wish to use i rather than 1i, then define it as a user variable or function by either i = 1i or i := 1i
To find the square root of -1, use sqrt(-1 + 0i).
Precision. Complex numbers which are very near to the real or imaginary axis are displayed as if they are on the axis. For example z = exp(-1i pi) displays the answer -1, but if we now look at z.imag then it may be a small but non-zero number, of the order of the numerical precision. For this reason the boolean expression
imag( exp(-1i pi) )==0
may evaluate as false. But
abs( imag( exp(-1i pi) ) ) < numeric_limits('eps')
evaluates as true.
Note, once you have defined a variable as complex it will remain internally treated as a complex type until it is cleared.

dictionary
calqit does not offer a built-in dictionary data type. Some of the functionality of a dictionary can be obtained by using keyed indexing (see key), but that will be unacceptably slow for large dictionaries.
see also: key

displace
The @+ and @- operators are used to add/subtract a row vector to every row of a matrix, or a column vector to every column of a matrix. (For example if the matrix is a set of coordinates or vectors, this could be used to displace all the coordinates or vectors.)
e.g.
a=[1 2 3;4 5 6]; b = [1;2]; a @+ b   # gives [2 3 4; 6 7 8]
a @+ [1 -1 2]                        # gives [2 1 5; 5 4 8]


functional
> In mathematics a function such as sin, exp, log, etc. is a 'number machine' that takes a single number as input and returns a single number as output. A functional is a 'number machine' that takes a whole function (and possibly one or more numbers) as input and returns a single number as output. The most well-known example is integration: if you provide some function f(x), then a mathematical notation such as I[f(x)] refers to the integral of the function between given limits. Other functionals include things like 'the value of x where f(x) is zero' and 'the minimum value of f(x)'.
The following built-in calqit functions act as functionals, i.e. they require or can be used with a function as input:
cheby, differ, fmin, fminbrac, fzero, min, plot, integ, qmin, rescale, sum, table
The syntax for these functionals has one of the following forms:
i) ff(func, [x1, x2])
ii) ff(func, x)
iii) ff(func, x, '', tol)
iv) ff(func, a, x)
v) ff(func, a, x, tol)
vi) ff(func, x, style)
vii) ff(func, x1, x2, style)
viii) ff(expr; x, x1, x2) or ff(expr; x, xvals)
where x1 and x2 are scalar. x can be a scalar in some cases, but is more often a pair [x1,x2] indicating x limits.
In the case of cheby another argument (n) is provided after x.
In the case of rescale a further argument (sc) is provided after x.
Cases (i)-(iii) are used when func expects a single argument. Cases (iv),(v) are used for functions such as poly(a,x) which take two arguments. Cases (vi),(vii) are used for the plot function.
Case (viii) shows an important general syntax which allows you to supply an arbitrary function as long as it can be expressed by a single expression taking a single parameter. expr is the expression, then you need a semicolon (N.B. not a comma). The symbol after the semicolon indicates the variable in your expression. After that you put the range or values. This is best understood by means of examples. The following list gives one example of each case (i) to (vii), then three examples of case (viii):
e.g.
fzero(sin, [2 5])
fzero(sin, [6 7], '', 1e-12)
fzero(poly, [1 1 -1], [1 4])        
fzero(poly, [1 1 -1], [1 4], 1e-12)
plot(sin, [1:10], 'r.')
plot(sin, 1,10, 'g,')
# case (viii):
fzero(x-cos x; x, [0,2])
plot(sin(t^2); t,-3,3)
plot(lor([1 0.5 2],z) + 0.01 z^2; z,0,4)


heaviside
For Heaviside function see fstep.

dot
The dot ('.') has several uses:
v.index an element of a vector or matrix
v.item an item from a list
v.sum call a function
(expr).sum call a function
.412857 a number between 0 and 1
a . b a matrix product
Note that to get a matrix product you need a space before the dot. The symbol ` (open inverted comma) also signifies the matrix product, so you can write a`b if you like.
see also: index

active
Most functions are passive. That is, they receive their inputs and generate output. Active functions change one of more of the variables provided as "input". For example
swaprows(v, [3,5]) does not leave v alone: it swaps rows 3 and 5 of v. To make this behaviour more apparent in your program code, you are encouraged to use the syntax
v.swaprows([3,5])
The return value of an active function is typically not the vector or matrix it acted on, but something much smaller, such as a boolean value or the matrix size. This allows active functions to be as fast as possible when acting on large matrices.
The following functions are active:

see also: sortit swaprows push pop nextPerm prevPerm shift_round
e.g.
x=1:5;; x=x.shuffle;? x.sortit; x

and
& is the AND operator, can be used on vectors, matrices
&& is the short-circuiting logical AND (only use for scalars)
@& is the bitwise AND operator
and is a synonym for &&

e.g.
[1 2 3] & [0 1 2]       # gives 0 1 1
[1 2 3] @& [0 1 2]      # gives 0 0 2
~x.isempty && x[1]==1   # only looks at x[1] if x is not empty
see also: or operator

Further information. The short-circuiting && and || always return 1 or 0. "Short-circuit" or "lazy evaluation" here means that in (A && B), the expression B is only evaluated if A returns 1, and in (A || B) the expession B is only evaluated if A returns 0.

binary
binary(n) returns a vector of 1's and 0's giving binary representation of integer n
binary(n, 1) same but in reverse order (so lowest bit first)
see also: unbinary bitweight pad

bitand
This is the bitwise AND operator. You can also use @&
see also: and operator

bitor
This is the bitwise OR operator. You can also use @|
see also: or operator

bitweight
bitweight(n) returns the bit weight (sum of binary digits) of integer n. It is equivalent to, but faster than, sum(binary(n)).
see also: binary

button

see also: mouse createButton onButton get

demo
To learn how to write calqit programs, you can examine any of the examples provided in folders (directories) such as "teach", "games", "demo". Each program in "demo" is a short program designed to teach one concept. You should first run it (by enetering "use filename" or just "filename" where filename is the name of the program), and then examine and modify the program to test your understanding.

debug
compiler directives:
e.g.
##end_input      finish input from script
##               everything is comment to next ## at a line start
##               also: provide help info for user function
                 (before the function declaration)
##if             planned          
##endif
see also: breakpoint

F9
Use the F9 function button to run whatever command or lines of script that are in the clipboard. For example, to run some code in a file being edited, first select it for copying in the editor, then click on the calqit window, then press F9.
see also: use

factorial
use ! for the factorial function
e.g.
10!
[0:5]!
see also: gamma lgamma bnc

false
boolean FALSE

formula
The word "formula" or "equation" can be used with the property function to load equations that are stored in the database. The equation is returned as a string, or as a list of strings if there is a group of equations.
e.g.
<< formula cosine_rule    # displays a^2 and returns the formula
[s,info] = property('formula','cosine_rule');
[s,info] = property('formula','sin');  # returns a list of formulae
see also: property

Gamma

see also: gamma lgamma gammaP gammaQ zeta

grid
grid(0), grid(1) turn grid off/on for current plot
see also: axis

in

see also: for

infinity
The standard set of values in calqit (present after a 'clear all') includes a symbol inf whose value is infinity. You can also obtain infinity by simple expressions such as 1/0. For minus infinity use -inf or -1/0. For example:
a = 1/0;; b = 1/0;; 1/a;; a==b
see also: integ

lazy
'lazy' evaluation is a programing concept which can make code more efficient or stable. When applied to logical structures it is also called 'short-circuit' evaluation. The standard example is in an expression such as
if x || y: disp('both')
In this case if x is true then there is no need to evaluate y, and it is not evaluated. This type of approach is applied to the && and || operators. For example writing
if x.1 > 2 ...
will generate an error if x is empty. The statement
if ~x.isempty() && x.1 > 2 ...
is safe because x.1 will only be evaluated when x is not empty.

lexicographic

see also: before strfind

marker
plot marker characters The plot(...) function uses a single-character code to indicate a marker symbol to be drawn at each data point, as follows:
+ a cross
x x-shaped cross
. dot
s square
t triangle
~ error bar
| vertical line
_ horizontal line
! a vertical line drawn from each data point to the x axis
The size of the marker character (except in the case '!') is given by an integer immediately following the character in the style string. The standard size is 5.

minus
see operator

mouse
Some mouse-related functions:
see also: getclick click getmouse setmouse onLDown onLUp onMove onDrag onLDouble onRDown onRUp onButton

Further information. If an error occurs while processing a mouse move or drag, then onMove or onDrag is disabled to prevent multiple errors. To re-enable them, recompile them.

numeric_limits
numeric_limits(i) returns internal precision information, depending on what index code you supply. The code is either a single integer or a word, as follows:
Let x be a positive number.
1. 'min' smallest x that can be represented in calqit
2. 'max' largest ,,
3. 'dmin' smallest x that can be internally represented in double precision
4. 'dmax' largest ,,
5. 'eps' approximate precision of individual internal calculations
6. 'mine' smallest power of 10 that can be represented
7. 'maxe' largest ,,
8. 'mini' smallest number that can be internally represented as an ordinary integer
9. 'int' largest ,,
10. 'bits' the number of bits in a "long int" (may be the same as in an "int") numeric_limits([]) returns the value of eps (i.e. numeric_limits(5)).
e.g.
numeric_limits([])
eps = numeric_limits('eps')

onButton
onButton(xy, info) The user-defined function onButton(xy, info) is called when a button is pushed, or a checkbox is checked. xy is the latest mouse position (i.e. when the button was pushed)
info = [id, state] where id identifies the button and state gives its state.
e.g.
onButton(xy, id) := disp('Button ', id.1, ' was clicked');
onButton(xy, id, state) := disp('Button ', id.1, ' now has state ', id.2);
see also: createButton

onDrag
If you define a function called onDrag, then it will be called when the mouse is dragged, except when dragging an item declared dragable (in which case onDragable is called instead). onDrag will be disabled if it generates an error. To re-enable it, re-compile it.
e.g.
t=seq(0,pi,20); crv=[cos(2t+2); sin 4t]%; p=plot(crv);
onDrag(xy) := replot(p,crv @+ xy);
p = plot(0,0,'^:b]'); onDrag(xy) := replot( p,rectangle(getmouse(6:7),xy) );
see also: onLDown onMove onLDouble onDragable

onDragable
If you define a function called onDragable, then it will be called when the user clicks or drags a dragable item.
In the case of a click, first onDragable is called, and then onLDown. You can use either of the forms:
onDragable(xy)
onDragable(xy, id)
In the second case the id of the item being dragged is passed.
e.g.
axis([0 9 0 9]); fix; dragable( plot(2,1,'s6'), [1 5 1 1]);
pp=plot([0 4],[5 5]); onDragable(xy):=replot(pp,[5 xy.1])
see also: dragable mouse onDrag

onKey
If you define a function called onKey, then it will be called when a key on the keyboard is pressed (as long as the figure window has the keyboard focus).
e.g.
p=text(1,1,'what colour do you like?','*35');
onKey(c) := set(p,'style',['' c '*35']);

onLDouble
If you define a function called onLDouble, then it will be called when the user double-clicks in the current figure window. The function must take a single argument, as in
onLDouble(xy)

see also: onLDown getmouse

onLDown
If you define a function called onLDown, then it will be called when the left mouse button is pressed (as long as the mouse is in the figure window). The function must take a single argument, as in
onLDown(xy)
The mouse position will be passed to the argument as a two-component vector. The function's return value is placed in the mouse memory, and can be retrieved using getmouse. You can also pass results to the rest of your program using setmouse or by using global variables (see 2nd example below).
e.g.
onLDown(xy) := plot(xy, 'b+10');
onLDown(xy) := global mxy; mxy = xy; plot(xy, 'ro5'); ;
see also: getclick click getmouse onLUp onLDouble onMove onDrag onKey onDragable onButton

Further information. Try the following to learn how to use onLDown. After executing the commands, click the figure.
e.g.

myshape = [0 1 0 1; 0 1 1 0]%;
fix; wipe 1; p=plot(myshape,'b2');
axis([0 1 0 1]*10);
onLDown(xy) := global p; replot(p,myshape @+ xy); 

onLUp
If you define a function called onLUp, then it will be called when the left mouse button is released. See onLDown for further information.
see also: onLDown

onMove
If you define a function called onMove, then it will be called when the mouse is moved in the figure window, unless onDrag is also defined and the left button is depressed. onMove will be disabled if it generates an error. To re-enable it, re-compile it.
e.g.
fix; onMove(xy) := plot(xy,'r.');
see also: onLDown onMove

operator
operator precedence:
e.g.
level  operators                   comments
-1   ++  --  !  '  ~  unary-  ??   inc, dec, factorial, transpose, not
0    ^  :  ^^                      power, sequence, matrix power
1    *  .  /  _/  //  @  vec       multiplication and division (see below)
2    +  -  mod  @+  @-             addition, remainder and subtraction (see below)
3    @&                            bitand
4    @|  @!                        bitor, bitxor
5    <  <=  ==  ===  ~=  >=  >  %  comparison and special divide
6    &&  &                         and
7    ||  |  xor  ?  ::             or, xor, test
8    ,                             next item
9    ;                             next row 
10   0                               
11    <<  >>  ;;                   input, output, display
12   /.  ...                       such that, continue line

Notice that : has high priority, so "1:10" mostly behaves the same as "(1:10)".
For example, x+1:10 means x+(1:10).
-3^2 evaluates to -9 not 9. The 'unary' minus sign mostly has a low priority (below ^ and !) but if it appears immediately after a multiply or divide then its priority goes up. Thus -2^2 # is -(2^2) = -4 but 1/-2^2 # is 1/(-2)^2 = 1/4 You are encouraged not to write expressions like that anyway. If you want 1/-(x^2) then write -1/x^2, much clearer. * is ordinary multiplication (elementwise) . is scalar product (it must be preceded by a space) @ is tensor product vec is vector product mod is modulo (i.e. the remainder after division) _/ is integer division // is 'divide by the whole expr that follows' % is 'divide the expr to the left by the expr to the right' && || scalar logical and, or with 'lazy' evaluation ? the query operator constuction is cond ? expr1 :: expr2

or
| is the OR operator, can be used on vectors, matrices
|| is the short-circuiting logical OR (only use for scalars)
@| is the bitwise OR operator
@! is the bitwise XOR operator
or is a synonym for ||
e.g.
[1 2 3] |  [0 1 2]          # gives 1 1 1
[1 2 3] @| [0 1 2]          # gives 1 3 3
x.isempty || x[1]==0        # only looks at x[1] if x is not empty
fid=fopen('myfile') or die  # evaluates 'die' if fopen fails
see also: and xor

Further information. The short-circuiting && and || always return 1 or 0. "Short-circuit" or "lazy evaluation" here means that in (A && B), the expression B is only evaluated if A returns 1, and in (A || B) the expression B is only evaluated if A returns 0.

pad
pad(s, len) pads s to length len
If s is a string, then by default pad with spaces.
If s is numerical, then by default pad with zeros.
If s is shorter than len, then return a truncated version.
N.B. pad is intended for work with integers or strings. For real numbers, use padd. pad(s, len, c) pad with item c
pad(s, len, c, 0) pad with item c at the front (rather than the back)

see also: trim size padd

path
At present calqit only looks for files in the current directory (which you can find out using cd). calqit remembers the current directory from one session to the next. If the path name becomes corrupted (cd returns an incorrect name) then use 'clear path'.

polyfit
For a straight line fit, use slf. To fit a polynomial, use lsfit(poly, ...). However, if the polynomial is above 2nd order, you should consider whether in fact a Chebyshev fit is better suited to your problem.
e.g.
x=-3:3; y=x^2+2x-3 + err(1,x.size);
cf = lsfit(poly,[0:2], x,y)   # returns polynomial fit coefficients
see also: lsfit cheby

pow

see also: operator

power

see also: operator

real
real(z) returns the real part of z.

see also: imag conj complex

recursion
Recursion can be used, but there is currently a bug in the use of recursive functions, and a work-around. If you use f(m) within function f, where m is a local variable, an error results, but f(m+0) succeeds. You can't pass the variable itself in such a call, but you can pass an expression.

e.g.
f(m) := f m<2: return 1; else return m*f(m-1);        # ok
f(m) := f m<2: return 1; else k=m-1; return m*f(k);   # fails 
f(m) := f m<2: return 1; else k=m-1; return m*f(k+0); # ok



refresh
To refresh the figure window, use replot() or update
see also: replot, update

repmat
repmat: see tensor

speed
Use tic, toc to time your programs. For improved speed:
1. Use constants where possible.
2. Prefer user functions with <= 2 arguments
3. Avoid growing matrices one item at a time: rather, size them at the outset using zero or reshape (or another method) and then fill in the entries.
4. Use pass by reference for very large matrices.
5. Don't worry about numerical expressions such as sqrt(2)/pi : they are evaluated at compile time so have no cost at all in run-time speed.
6. Organize matrices by columns rather than by rows (e.g. plotting a single matrix by columns is slightly quicker than by rows).

Further information. To test timing at the calqit prompt, to avoid including the compilation time you can use braces as in
tic; sort(rand(100)); toc;; . This ensures the whole line is compiled before it is run.
In the followng list, N = ncol*nrow refers to the number of items in a vector or matrix, n = ncol = nrow refers to the size of a square matrix (so N = n^2);
Very fast: O(1)
transpose of a vector (for a matrix it is O(n))
push, pop on a stack or queue (for a vector it is O(n))
reshape (as long as the size doesn't change)
passing arguments by reference
Fast: O(log N)
qfind
Intermediate: O(N)
All operators except matrix multiplication.
Most functions not mentioned under fast or slow.
det('') is O(n)
passing arguments by value
Slow:
sort O(N log N) usually; O(N^2) worst case.
O(n^2):
solve('',v)
inv('')
cheby
O(n^3):
matrix multiplication
LUform
solve, det, inv unless the matrix is pre-processed
lsfit

string
strings
Declare a string by s='blah' or s="blah" (either type of inverted commas are ok). Most functions work in a sensible way with strings. For a list of strings of different lengths, use a list rather than a matrix. Splice (concatenate) strings using [s1, s2]; split them using array indexing. Find characters using find, find substrings using strfind and strfind_last. Compare using s1==s2 or s1===s2 or s1.before(s2).
To express a number n as a string use str(n). To convert a string such as '2.5' to the number 2.5 use str2num(s).
To convert from 'ascii' integer codes to string use s = ['', n]. To convert from string to integer codes use n = 0+s.

see also: list find strfind strfind_last === before isstring str num2str

tensor
tensor product
x @ y performs a tensor product. That is to say, a new matrix is generated made from copies of x at the locations specfied by y, each copy having been multiplied by the relevant element of y. e.g. if x is any matrix, and
y = 2 0 1 then x @ y = 2x 0 x
0 1 3 0 x 3x
The size of the new matrix is (x.nrow*y.nrow , x.ncol*y.ncol)

e.g.
a = ones(5); b = [2 0 1; 0 4 3];  a @ b

Further information. Terminology Sometimes the outer product is referred to as a "tensor product" but in strict terminology that is incorrect. An outer product is a combination such as
M_j = A_{i} B_{j}
If A and B are column vectors then their outer product is A . B'
In Dirac notation the inner product, outer product and tensor product are written, respectively:
< A|B>
|A>< B|
|A> x |B> The tensor product of two magic squares is also magic.

transpose
a' means the transpose of a
a" means the adjoint of a
e.g.
a=[1,2,3;4,5,6];; a';;
m=[10,20,30]; a=[1,2,3;4,5,6];  m . a'
see also: operator adjoint

types
calqit variables have four possible base types, and within these various derived types. The base types are
integer, double, complex, list.
The derived types are:
0 numeric (matrix, vector, scalar)
1 string
2 boolean
3 complex
4 unused
5 list

vec
a vec b gives the vector product (cross product) of a and b. You can also use
a @^ b
The vector product is only defined for vectors with three elements. If you supply matrices with three rows or colomns, then calqit will treat them as a list of 3-element vectors.
e.g.
u=[1 2 3]; v=[4 5 6]; u vec v
m = v% @ (1:5); u vec m
see also: operator cross

xor
The bitwise xor operator is @!
e.g.
[1 0 1 0] @! [1 1 0 0]  # gives [0 1 1 0]
see also: or

=
a = b sets a equal to b
a==b compares the elements one by one (a and b must have matching size and shape), returning a boolean matrix.
a===b compares the size, shape and type and all the contents; if everything matches then returns 1., otherwise returns 0. This is faster than all(all(a==b)) so is preferred for large matrices.
e.g.
a = 1:5; b=a; a==b     # returns [1 1 1 1 1]
a===b                  # returns 1

==
a == b returns 1 for each element where a and b agree
see also: === operator

===
a === b returns 1 if a is the same as b in every respect (same shape, same type, same elements)
see also: all operator

@ is the tensor product operator
@^ is the vector product operator (also vec)
@+ @- is the displacement operator
(add/subtract a vector to all cols or rows)
@* @/ multiply/divide cols or rows by vector
@& @| bitwise and/or
@! bitwise xor (exclusive or)

see also: tensor displace operator and or vec

expr % expr divide expr on the left by expr on the right

! is the factorial operator

For uses of dot see ?dot.
see also: dot

ai means i'th row of a
a

see also: solve

[home] [top]