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
numeric matrix |
string matrix |
boolean matrix |
stack |
queue |
list |
scalar const |
e.g.
j=0; while 1: j += 1; if j>10: break; disp('j=',j);see also: breakpoint
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 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
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 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;
see also: quit
see also: isdefined
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);
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
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
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.
?? get some more help
?name get help on name
??name get more help on name
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");
see also: if
e.g.
persistent x,ysee also: const global
quits calqit (equivalent to closing the window).
The keyword "return" is used on its own. The function's return value[s] will have been specified via the function definition.
see also: use
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 redsee 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.
see also: sysCommand
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
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
e.g.
j=1; while j<10: j*=2 j=1; while j<10: j*=2; disp('j=',j);see also: break for
see also: help Type help for basic help.
Further information. Type help for basic help
see also: floor ceil arg
see also: cos asin atan
see also: cosh
e.g.
z = (1 + 1i)magic(3); z;; ' ';; z"see also: transpose
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,0see also: any find, =.
e.g.
a = 77*89;; b = ans/77
see also: all find.
see also: abs complex
see also: complex plot
see also: sin acos atan
see also: sinh
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
see also: tan asin acos
see also: tanh
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 offsee 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(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
e.g.
before('ant','ankle') a=[1 3 5 7]; b=[1 4 0]; a.before(b)see also: strfind === operator next_perm
use bezier
e.g.
use bezier plot( bezier([1 2 4 2; 1 3 4 5], 50) )see also: bezfit
= 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').
see also: loadBitmap snipImage getpixel
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 trianglesee also: prod gamma lgamma binomial
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:see also: dir clear exepath
cd exepath(1)
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
see also: diag
see also: floor round
see also: floor round ??
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(0) closes all figures (and so does close(-1)).
see also: figpos wipe unfix
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
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
see also: complex adjoint
see also: sin tan acos cosh
cosh(x) = (exp(x) + exp(-x))/2
see also: sinh tanh acosh
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
a and b can be matrices of either 3 rows or 4 columns
see also: vec
see also: sum
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
e.g.
m = load("mydata.txt") # don't forget the inverted commas here plot(msee also: load save plot xlabel print texplot
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: inv LUform solve
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
see also: diff2 differ
see also: diff differ
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=3see 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 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
e.g.
disp('this is all',''); disp(' on one line'); x=1; disp('x=', x, ', exp(x)=', exp(x));see also: dispfile messageBox
dispfile(name, linenum) Display the lines near linenum in file.
see also: disp cd dir
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
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-5see also: eigvec eigvv
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 insteadsee also: eigval eigvv
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.eigvvsee also: eigval eigvec
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
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(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
see also: erf gammaP erfinv
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(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
see also: errbar
e.g.
n=50;x=1:n; y=10sin(x/5)+err(n); dy=rand(n); errbar(x,y,dy);see also: plot
***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.
display a warning message (when level=0) or throw an error (when level > 0)
see also: assert
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(0) does the same
exepath(1) returns the path of the Calqit executable (application)
see also: cd
see also: log
e.g.
eye(4) # 4x4 identity matrix eye(4,0:4) # upper triangle of 1ssee also: zero diag
fclose(-1) closes all files
see also: fopen fread fwrite load save
see also: fopen fread
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
see also: fft
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
see also: figpos plot wipe
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 effectsee also: plot colour
see also: qfind rfind findall strfind
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
see also: strfind
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
see also: ceiling round
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(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
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
see also: fft ifft
see also: fft ifft
fread(fid, n) read n bytes from a binary file
see also: fopen fclose readtext load save feof
see also: sign tophat
e.g.
fwrite(fid, 'Hello
see also: fopen fclose load save
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 thingsee 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
see also: gamma gammaP gammaQ
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
= (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
= (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
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%.
e.g.
axis([0 10 0 10]); id=createButton([1,9 1.5 .6], 'c', 'check') get(id)see also: createButton set
e.g.
disp('yes or no?', ''); ch = getch;see also: getline getkeyb
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
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
e.g.
s = getline('enter a string:'); disp('You wrote "', s, '".');see also: getch getkeyb
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').
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(h1 + 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]
see also: fix unfix
see also: real complex
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(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
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.
e.g.
a = 1:5; b = 3:6; a.intersect(b)see also: unique issubset union setminus setxor
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(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
see also: type ischar
see also: type isboolean
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';;
see also: isscalar isvector isdefined
see also: str2num
see also: primeFactors primeList
see also: isempty isvector isdefined
see also: ischar type
see also: sort sortit unique intersect union setminus setxor
see also: isempty isscalar
x.join(s) also inserts separator s between items
see also: split list
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']
see also: tensor
see also: tensor
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
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 setsee 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).
see also: log log10
see also: seq
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 ignoredsee also: save readcsv
see also: snipImage
see also: exp lg2 log10
see also: ln lg2
e.g.
loglog(x^4;x,1,90);see also: plot semilogy semilogx
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
e.g.
semilogx(x;x,1,90);see also: plot loglog semilogy
e.g.
semilogy(exp(-x^2);x,-3,3);see also: plot loglog semilogx
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
[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 . usee also: solve inv det
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.
e.g.
magic(3);; '--';; magic(4)
max(m) for a matrix gives the highest value in each column.
see also: maxind min mean range
see also: max min minind
see also: sum size std
e.g.
headings = ['File';'Help'] m1=list( '&cd->cd', '&Dir->dir' ); m2=list( '&Help->??', '&Cos->plot(cos,0,9)' ); menu(headings, list(m1,m2));
e.g.
messageBox('hello there')see also: disp
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
see also: min max maxind
see also: bnc
see also: nrow size
e.g.
x=1:4; for i=1:(4!) x;; x.nextPerm;see also: prevPerm shuffle swap_row swap_col before
e.g.
norm(1,4,8) # sqrt(1+16+64) = 9 norm(1:24)see also: sumsq stdev gauss err normal
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
see also: ncol size
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# 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
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
see also: integ
Further information. The case of equations with explicit time-dependence is under development.
see also: zeros
(only accurate up to system clock ticks)
pause(0) wait for next tick
see also: tic toc waitgetclick getclick click
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 linesee 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
= 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
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
e.g.
polyshow([2 3 0 -5 8])see also: poly
y = x.pop is equivalent to y = x(end); x
see also: stack queue qpop push top clear
see also: numeric_limits, str
see also: nextPerm shuffle
see also: isprime primeFactors primeList
To use primeFactors, first use isprime, and then ?primeFactors will give further information.
see also: isprime, primeFactors
To use primeList, first use isprime.
see also: isprime, primeFactors
e.g.
plot(gauss(1,x)/sqrt(2pi); x,-4,4); xlabel('x'); print 'myfig';see also: plot texplot
prod(f, n, x) the product of f(n_i, x)
see also: sum
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
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(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
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
see also: pop push queue
syntax: besselj0(x), besselj1(x), besselj(n,x)
see also: besselj0 besselj1 besselj
syntax: besselj0(x), besselj1(x), besselj(n,x)
see also: besselj0 besselj1 besselj
e.g.
plot(besselj0, 0, 20)see also: besselj1 besselj airy
e.g.
plot(besselj1, 0, 20)see also: besselj0 besselj airy
e.g.
plot(besselj(3,x); x,0,20)see also: besselj0 besselj1 airy
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)) dxsee 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
m = qload(filename)
or after "qsave m" use "m = qload m";
see also: qsave load
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
see also: push qpop isempty stack end
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
e.g.
x=randexp(1,1000); h = x.hist; histplot hsee also: rand err
see also: shuffle
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
[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
see also: fread writetext load
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 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
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);
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)
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
Returns the vector (or matrix) with elements in reverse order.
see also: find findall
e.g.
x = rndsee also: rand irand err
see also: floor ceiling
see also: sum colsums
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(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
e.g.
x = seq(0,10,100); plot(x, cos x, 'o');
see also: intersect setxor union
e.g.
setmouse('hello'); disp('retrieved ', getmouse('m')); setmouse(pi); disp( 'retrieved ', getmouse('m') );see also: getmouse onLDown
e.g.
a = 1:5; b = 3:6; a.setxor(b)see also: intersect setminus union
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.
see also: size nrol ncol
see also: shuffle swap_col swap_row reverse
see also: useColour plot wipe
shuffles the items in a vector or a list, or the COLUMNS of a matrix
see also: reverse irand next_perm shift_round
see also: abs fstep tophat
see also: cos tan asin sinh sinc
see also: sin
see also: cosh tanh
see also: sum mean nrow ncol
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 plotsee 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
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
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(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
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.xsee also: LUform inv det
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 7see also: sortit sortind sortrows unique reverse
e.g.
x = irand(50,[1,20]); i = x.sortind; [x; i; x.i]see also: sort sortit active
e.g.
x=[2 1 4 5 7 5]; x.sortit # returns 6, and x is now 1 2 4 5 5 7see also: sort sortind sortrows reverse active
This is an active function.
e.g.
m=irand(10,[8,4]); mm=m; ind = m.sortrowssee also: sort sortind sortit active uniquerows
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
see also: push pop top queue
see also: mean size variance
see also: sign fstep tophat
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".
e.g.
strlist( list('hi','there','bud') )see also: list str2num
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".
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 ===
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 ===
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)
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 itsee also: mean stdev size colsums rowsums
e.g.
sumsq([3, 4])see also: sum variance
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
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
see also: sin cos atan tanh.
see also: sinh cosh tan.
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
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
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,'2pi+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(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(m, h, rh) provide column and row headers
textable(m, N) specify precision
see also: texplot tex
e.g.
tic; a=1:1000; a.shuffle; a.sortit; tocsee also: toc pause oclock
see also: tic toc oclock today
title(string, style)
e.g.
plot( [0 1 2], [0 1 0] ); title 'My graph'see also: plot text xlabel ylabel
see also: tic pause.
see also: tic pause.
see also: oclock
see also: pop stack queue end
see also: sign step
see also: det
e.g.
s = ' hi there '; t = trim(s); ['>',t,'<']see also: split pad
To find out about types of variable, use ?types.
(To display a file, use dispfile).
see also: types isdefined ischar isboolean dispfile
e.g.
unfix; plot((x-2)^2; x,0,4);see also: fix wipe plot subplot
e.g.
x=[1 2 3]; y=[1 3 4 5]; union(x,y) # returns 1 2 3 4 5see also: sort intersect unique
e.g.
v=[1 4 2 5 2 1 6]; unique(v) # returns 1 2 4 5 6see also: union issubset uniquerows
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 is faster than replot(), because it does not repaint the whole figure.
see also: replot getmouse
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.
see also: stdev mean sumsq
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
see also: pause tic toc
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([]) 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
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('text', style) to set size, colour etc.
see also: ylabel title
ylabel('text', style) to set size, colour etc.
see also: xlabel title
zeros(r,c) or zeros([r,c]) returns an (r x c) matrix of zeros
see also: ones diag eye rand pad
see also: gamma
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 RR
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
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
see also: acosh
see also: asinh
see also: atanh
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
see also: sum rowsums
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.
see also: key
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]
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)
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
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
&& 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 emptysee 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(n, 1) same but in reverse order (so lowest bit first)
see also: unbinary bitweight pad
see also: and operator
see also: or operator
see also: binary
see also: mouse createButton onButton get
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 ##endifsee also: breakpoint
see also: use
e.g.
10! [0:5]!see also: gamma lgamma bnc
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 formulaesee also: property
see also: gamma lgamma gammaP gammaQ zeta
see also: axis
see also: for
a = 1/0;; b = 1/0;; 1/a;; a==b
see also: integ
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.
see also: before strfind
+ 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.
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.
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')
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
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
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
e.g.
p=text(1,1,'what colour do you like?','*35'); onKey(c) := set(p,'style',['' c '*35']);
onLDouble(xy)
see also: onLDown getmouse
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);
see also: onLDown
e.g.
fix; onMove(xy) := plot(xy,'r.');see also: onLDown onMove
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
|| 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 failssee 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.
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
e.g.
x=-3:3; y=x^2+2x-3 + err(1,x.size); cf = lsfit(poly,[0:2], x,y) # returns polynomial fit coefficientssee also: lsfit cheby
see also: operator
see also: operator
see also: imag conj complex
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
see also: replot, update
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
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
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.
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
integer, double, complex, list.
The derived types are:
0 numeric (matrix, vector, scalar)
1 string
2 boolean
3 complex
4 unused
5 list
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 msee also: operator cross
e.g.
[1 0 1 0] @! [1 1 0 0] # gives [0 1 1 0]see also: or
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
see also: === operator
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
a
see also: solve