While a few other functions already exist in FEX that compute the intersection points of curves, this short piece of code was written with speed being the highest priority. No loops are used throughout, taking full advantage of MATLAB's vectorization capabilitiesI welcome any comments, suggestions, bug reports etc.------------------------------------------------------------------------------INTERX Intersection of curves P = INTERX(L1,L2) returns the intersection points of two curves L1 and L2. The curves L1,L2 can be either closed or open and are described by two-row-matrices, where each row contains its x- and y- coordinates. The intersection of groups of curves (e.g. contour lines, multiply connected regions etc) can also be computed by separating them with a column of NaNs as for example L = [x11 x12 x13 ... NaN x21 x22 x23 ...; y11 y12 y13 ... NaN y21 y22 y23 ...] P has the same structure as L1 and L2, and its rows correspond to the x- and y- coordinates of the intersection points of L1 and L2. If no intersections are found, the returned P is empty. P = INTERX(L1) returns the self-intersection points of L1. To keep the code simple, the points at which the curve is tangent to itself are not included. P = INTERX(L1,L1) returns all the points of the curve together with any self-intersection points. Example: t = linspace(0,2*pi); r1 = sin(4*t)+2; x1 = r1.*cos(t); y1 = r1.*sin(t); r2 = sin(8*t)+2; x2 = r2.*cos(t); y2 = r2.*sin(t); P = InterX([x1;y1],[x2;y2]); plot(x1,y1,x2,y2,P(1,:),P(2,:),'ro')

This generates m random n-element column vectors of values, [x1;x2;...;xn], each with a fixed sum, s, and subject to a restriction a<=xi<=b. The vectors are randomly and uniformly distributed in the n-1 dimensional space of solutions. This is accomplished by decomposing that space into a number of different types of simplexes (the many-dimensional generalizations of line segments, triangles, and tetrahedra.) The 'rand' function is used to distribute vectors within each simplex uniformly, and further calls on 'rand' serve to select different types of simplexes with probabilities proportional to their respective n-1 dimensional volumes. This algorithm does not perform any rejection of solutions - all are generated so as to already fit within the prescribed hypercube.

This function computes the (x,y) locations where two curves intersect. The curves can be broken with NaNs or have vertical segments. It is also very fast (at least on data that represents what I think is a typical application).

A common request is to interpolate a set of points at fixed distances along some curve in space (2 or more dimensions.) The user typically has a set of points along a curve, some of which are closely spaced, others not so close, and they wish to create a new set which is uniformly spaced along the same curve.When the interpolation is assumed to be piecewise linear, this is easy. However, if the curve is to be a spline, perhaps interpolated as a function of chordal arclength between the points, this gets a bit more difficult. A nice trick is to formulate the problem in terms of differential equations that describe the path along the curve. Then the interpolation can be done using an ODE solver.As an example of use, I'll pick a random set of points around a circle in the plane, then generate a new set of points that are equally spaced in terms of arc length along the curve, so around the perimeter of the circle.theta = sort(rand(15,1))*2*pi;theta(end+1) = theta(1);px = cos(theta);py = sin(theta); 100 equally spaced points, using a spline interpolant.pt = interparc(100,px,py,'spline');% Plot the resultplot(px,py,'r*',pt(:,1),pt(:,2),'b-o')axis([-1.1 1.1 -1.1 1.1])axis equalgrid onxlabel Xylabel Ytitle 'Points in blue are uniform in arclength around the circle'You can now also return a function handle to evaluate the curve itself at any point. As well, CSAPE is an option for periodic (closed) curves, as long as it is available in your matlab installation.[~,~,foft] = interparc([],px,py,'spline');foft(0:0.25:1)ans = 0.98319 0.18257 -0.19064 0.98151 -0.98493 -0.17486 0.18634 -0.98406 0.98319 0.18257

MAT2TILES is basically a wrapper for mat2cell but with a more convenient interface when you are simply trying to decompose an N-dimensional array into equal-sized chunks. It takes the desired chunk-size as an input argument, whereas mat2cell does not. MAT2TILES also has some convenient shortcuts for when you only want to tile along particular dimensions (see below).USAGE: C=mat2tiles(X,D1,D2,D3,...,Dn) C=mat2tiles(X,[D1,D2,D3,...,Dn]) will produce a cell array C containing adjacent chunks of the array X, with each chunk of dimensions D1xD2xD3x...xDn. If a dimension Di does not divide evenly into size(X,i), then the chunks at the upper boundary of X along dimension i will be truncated. It is permissible for the Di to be given value Inf. When this is done, it is equivalent to setting Di=size(X,i). This is useful if you want to tile along only certain array dimensions. EXAMPLE 1: Split a 28x28 matrix into 4x7 sub-matrices >> A=rand(28); C=mat2tiles(A,[4,7]) C = [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] [4x7 double] EXAMPLE 2: Split a 20x20x6 array into 20x6x3 sub-arrays. This example illustrates how 'Inf' can be used to indicate that one of the sub-array dimensions is to be the same as in the original array, in this case size(A,1)=20. >> A=rand(20,20,6); >> C=mat2tiles(A,[Inf,6,3]) %equivalent to mat2tiles(A,[20,6,3]) C(:,:,1) = [20x6x3 double] [20x6x3 double] [20x6x3 double] [20x2x3 double] C(:,:,2) = [20x6x3 double] [20x6x3 double] [20x6x3 double] [20x2x3 double] The example also shows a situation where the original array does not divide evenly into sub-arrays of the specified size. Note therefore that some boundary sub-chunks are 20x2x3.

ALLCOMB - All combinations B = ALLCOMB(A1,A2,A3,...,AN) returns all combinations of the elements in the arrays A1, A2, ..., and AN. B is P-by-N matrix, where P is the product of the number of elements of the N inputs. This functionality is also known as the Cartesian Product. The arguments can be numerical and/or characters, or they can be cell arrays. Examples: allcomb([1 3 5],[-3 8],[0 1]) % numerical input: % -> [ 1 -3 0 % 1 -3 1 % 1 8 0 % ... % 5 -3 1 % 5 8 1 ] ; % a 12-by-3 array allcomb('abc','XY') % character arrays % -> [ aX ; aY ; bX ; bY ; cX ; cY] % a 6-by-2 character array allcomb('xy',[65 66]) % a combination % -> ['xA' ; 'xB' ; 'yA' ; 'yB'] % a 4-by-2 character array allcomb({'hello','Bye'},{'Joe', 10:12},{99999 []}) % all cell arrays % -> { 'hello' 'Joe' [99999] % 'hello' 'Joe' [] % 'hello' [1x3 double] [99999] % 'hello' [1x3 double] [] % 'Bye' 'Joe' [99999] % 'Bye' 'Joe' [] % 'Bye' [1x3 double] [99999] % 'Bye' [1x3 double] [] } ; % a 8-by-3 cell array ALLCOMB(..., 'matlab') causes the first column to change fastest which is consistent with matlab indexing. Example: allcomb(1:2,3:4,5:6,'matlab') % -> [ 1 3 5 ; 1 4 5 ; 1 3 6 ; ... ; 2 4 6 ] If one of the arguments is empty, ALLCOMB returns a 0-by-N empty array. See also nchoosek, perms, ndgrid and nchoose, combn, kthcombn (matlab Central FEX)

GRABIT Extracts data points from an image file.GRABIT starts a GUI program for extracting data from an image file. It is capable of reading in BMP, JPG, TIF, GIF, and PNG files (anything that is readable by IMREAD). Multiple data sets can be extracted from a single image file, and the data is saved as an n-by-2 matrix variable in the workspace. It can also be renamed and saved as a MAT file.Following steps should be taken: 1. Load the image file. 2. Calibrate axes dimensions. You will be prompted to select 4 points on the image. 3. Grab points by clicking on points. Right-click to delete a point. Image can be zoomed during this stage. 4. Multiple data sets will remain in memory so long as the GUI is open. Variables can be renamed, saved to file, or edited in Array Editor.Panning is achieved by clicking and dragging on the image. In addition to using the zoom button, there are keyboard shortcuts for zooming: - center view - zoom in - zoom out - reset viewThis code will also work for extracting data points from a tilted or a skewed image (even upside-down or mirrored). The calibration stage ensures that the imperfect orientation or quality of the image is accounted for.The types of files that will most likely work are BMP, JPG, TIF, GIF (up to 8-bit), and PNG files. Basically, any format supported by the IMREAD is accepted.GRABIT(FILENAME) will start the GUI program and open the image file FILENAME. Type GRABIT('-sample') to load a sample image.Created in MATLAB® R13. Tested up to R2006a

num2strexact is a self-building C-mex function that converts a double or single input to the exact decimal string. The conversion is done with hundreds of digits of precision to maintain the exact conversion. The conversion uses the exact decimal value of each bit of the IEEE double precision floating point format along with the exact application of 2^exponent. Inf and NaN bit patterns are recognized, and denormalized numbers are handled also.Don't confuse the exact conversion with significance! Double numbers will only be significant to about 15 decimal digits, and single numbers will only be significant to about 7 decimal digits. For example,>> format hex>> 1.2ans = 3ff3333333333333>> num2strexact(1.2)ans = 1.1999999999999999555910790149937383830547332763671875>> 1.2 + eps(1.2)ans = 3ff3333333333334 <-- one bit different from 1.2num2strexact(1.2 + eps(1.2))ans = 1.20000000000000017763568394002504646778106689453125>> num2strexact(eps(1.2))ans = 2.220446049250313080847263336181640625e-16You can see that 1.2 is not represented exactly in IEEE double format. The difference shows up in the 18th digit for this example. Then note that the very next number in the IEEE double format model is about 2e-16 bigger. The exact conversions are shown for each number, but they are not significant beyond the 16th digit shown. There are no numbers in between these two numbers that can be represented in IEEE double format.Syntax: Y = num2strexact(X [,'fixed' or 'float']) [Y1 Y2] = num2strexact(X1,X2 [,'fixed' or 'float']) [Y1 Y2 Y3] = num2strexact(X1,X2,X3 [,'fixed' or 'float']) : : etc etcX = double or single or halfNOTE: The half type can be input in one of two ways: 1) A uint16 class variable containing the half bit patterns 2) A half class variable. num2strexact must have access to the underlying bit patterns, so if you input a half class variable, then this will first be converted to the equivalent integer bit patterns with the storedInteger function (a temporary deep copy).The number of inputs must match the number of outputs, except in thespecial case of 1 input and 0 outputs where the result will simply beput into ans. If the input is a scalar, the output will be a char string.If the input is any other size array, the result will be a cell array ofthe same dimensions as the input, with each cell containing the charstring conversion of the corresponding element.The optional 'fixed' argument forces the result to be fixed point.The optional 'float' argument forces the result to be floating point. Allnumbers will be printed with exponents, even if the exponent is 0.The default will be fixed or floating point depending on the size of thedecimal exponent. Numbers with -1 <= (decimal exponent) <= 2 will bedisplayed as fixed point, else the number will be displayed as floatingpoint.All NaN bit patterns, regardless of the sign bit and payload, will bereturned simply as the string 'NaN'.Infinity bit patterns will be returned as 'Inf' or '-Inf' as appropriate.num2strexact gives similar results to the following NUM2IEEE function by Steven Lord:http://www.mathworks.com/matlabcentral/fileexchange/2996except that num2strexact does not require the Symbolic Math Toolbox to display the potentially hundreds of exact digits, and num2strexact runs much faster.

PADCAT - concatenate vectors with different lengths by padding with NaN M = PADCAT(V1, V2, V3, ..., VN) concatenates the vectors V1 through VN into one large matrix. All vectors should have the same orientation, that is, they are all row or column vectors. The vectors do not need to have the same lengths, and shorter vectors are padded with NaNs. The size of M is determined by the length of the longest vector. For row vectors, M will be a N-by-MaxL matrix and for column vectors, M will be a MaxL-by-N matrix, where MaxL is the length of the longest vector. Examples: a = 1:5 ; b = 1:3 ; c = [] ; d = 1:4 ; padcat(a,b,c,d) % row vectors % -> 1 2 3 4 5 % 1 2 3 NaN NaN % NaN NaN NaN NaN NaN % 1 2 3 4 NaN CC = {d.' a.' c.' b.' d.'} ; padcat(CC{:}) % column vectors % 1 1 NaN 1 1 % 2 2 NaN 2 2 % 3 3 NaN 3 3 % 4 4 NaN NaN 4 % NaN 5 NaN NaN NaN [M, TF] = PADCAT(..) will also return a logical matrix TF with the same size as R having true values for those positions that originate from an input vector. This may be useful if any of the vectors contain NaNs. Example: a = 1:3 ; b = [] ; c = [1 NaN] ; [M,tf] = padcat(a,b,c) % find the original NaN [Vev,Pos] = find(tf & isnan(M)) % -> Vec = 3 , Pos = 2This second output can also be used to change the padding value into something else than NaN. [M, tf] = padcat(1:3,1,1:4) M(~tf) = 99 % change the padding value into 99 Scalars will be concatenated into a single column vector. See also cat, reshape, strvcat, char, horzcat, vertcat, isempty nones, group2cell (Matlab File Exchange)

This contribution was inspired by a series of posts by Bruno Luong and Jan Simon. Often, we wish to divide an array into equal sized sub-blocks and perform an operation on these blocks, reducing them to scalars. For general block operations, MATLAB has made available functions like BLOCKPROC. It is often also possible to do this kind of processing by using MAT2CELL to subdivide the array into cells, each containing a block, and then applying CELLFUN.For certain specific and common kinds of operations, however, it is possible to do the computation in a particularly efficient manner. These functions include sum(), prod(), mean(), max(), min(),... which can be done separably along each dimension of the block, first along columns, then along rows, etc... For example, sum(B)=sum(sum(sum(B,1),2),3) By decomposing these functions into separable calls, it is possible to do them blockwise in an array with a minimum of data copying and a high degree of vectorization and sequential memory access. The mfunction SEPBLOCKFUN in this submission optimizes the computation in this way for any separable function the user cares to supply. USAGE: Y=sepblockfun(X,blockdims,fun) IN: X: A full array. If the ndSparse class defintion is on the path, then X can also be a regular sparse matrix or ndSparse array. Performance might not be as strong as for full arrays, however. blockdims: a vector of integers specifying the dimensions of the sub-blocks. The array X must partition evenly into blocks of this size. If blockdims(i) is set to Inf then it will be replaced with blockdims(i)=size(X,i). fun: function handle to an operation assumed to be separable (Examples: max,min,sum,prod,mean, etc...). The function must accept the input syntax fun(B,DIM) where B is an input array and DIM is a dimension along which to operate. Alternatively, fun can be one of the following strings 'max','min','sum','mean', 'prod'. OUT: Y: the output array. Y(i)=fun(Xi(:),1) where Xi is the i-th sub-block of the input array X. EXAMPLE 1: Divide a 400x400x400 array into 10x10x10 blocks. Return the blockwise, mean, max., and min. of each block, each organized as a 40x40x40 array. A=rand(400,400,400); Ameans=sepblockfun(A,[10,10,10],@mean); Amins=sepblockfun(A,[10,10,10],'min' ); Amaxs=sepblockfun(A,[10,10,10], @(B,d) max(B,[],d) ); EXAMPLE 2: Not all operations satisfy the separability property, but sometimes inseparable operations can be decomposed into separable ones. As an example, we take the blockwise standard deviations of the same array from Example 1. Astds=sqrt( sepblockfun(A.^2,[10,10,10],'mean') - Ameans.^2 ); It is also possible to use SEPBLOCKFUN for sparse matrices and arrays if you happen to have my ndSparse class installed. However, sparse arrays may benefit less from the computation strategy than full arrays, in part because RESHAPE operations are less efficient for sparse matrices. Also, it is only possible to apply separable functions that have been overloaded for the ndSparse class.

Generates the roto-translation matrix for the rotation around an arbitrary line in 3D. The line need not pass through the origin. Optionally, also, applies this transformation to a list of 3D coordinates. SYNTAX 1: M=AxelRot(deg,u,x0) in: u, x0: 3D vectors specifying the line in parametric form x(t)=x0+t*u Default for x0 is [0,0,0] corresponding to pure rotation (no shift). If x0=[] is passed as input, this is also equivalent to passing x0=[0,0,0]. deg: The counter-clockwise rotation angle about the line in degrees. Counter-clockwise is defined using the right hand rule with respect to the line direction vector u. out: M: A 4x4 affine transformation matrix representing the roto-translation. Namely, M will have the form M=[R,t;0 0 0 1] where R is a 3x3 rotation and t is a 3x1 translation vector. SYNTAX 2: [R,t]=AxelRot(deg,u,x0) Same as Syntax 1 except that R and t are returned as separate arguments. SYNTAX 3: This syntax requires 4 input arguments be specified, [XYZnew, R, t] = AxelRot(XYZold, deg, u, x0) where the columns of the 3xN matrix XYZold specify a set of N points in 3D space. The output XYZnew is a 3xN matrix of transformed points, i.e., the input points rotated about the axis. All other input/output arguments have the same meanings as before.

** Big speed boost courtesy of Oliver Woodford. Recommended to update to latest version ** stlwrite(FILE, FV) writes a stereolithography (STL) file to FILE for a triangulated patch defined by FV (a structure with fields 'vertices' and 'faces'). stlwrite(FILE, FACES, VERTICES) takes faces and vertices separately, rather than in an FV struct stlwrite(FILE, X, Y, Z) creates an STL file from surface data in X, Y, and Z. stlwrite triangulates this gridded data into a triangulated surface using triangulation options specified below. X, Y and Z can be two-dimensional arrays with the same size. If X and Y are vectors with length equal to SIZE(Z,2) and SIZE(Z,1), respectively, they are passed through MESHGRID to create gridded data. If X or Y are scalar values, they are used to specify the X and Y spacing between grid points. stlwrite(...,'PropertyName',VALUE,'PropertyName',VALUE,...) writes an STL file using the following property values: MODE - File is written using 'binary' (default) or 'ascii'. TITLE - Header text (max 80 chars) written to the STL file. TRIANGULATION - When used with gridded data, TRIANGULATION is either: 'delaunay' - (default) Delaunay triangulation of X, Y 'f' - Forward slash division of grid quads 'b' - Back slash division of quadrilaterals 'x' - Cross division of quadrilaterals Note that 'f', 'b', or 't' triangulations now use an inbuilt version of FEX entry 28327, "mesh2tri". FACECOLOR - Single colour (1-by-3) or one-colour-per-face (N-by-3) vector of RGB colours, for face/vertex input. RGB range is 5 bits (0:31), stored in VisCAM/SolidView format (http://en.wikipedia.org/wiki/STL_(file_format)#Color_in_binary_STL) Example 1: % Write binary STL from face/vertex data tmpvol = false(20,20,20); % Empty voxel volume tmpvol(8:12,8:12,5:15) = 1; % Turn some voxels on fv = isosurface(~tmpvol, 0.5); % Make patch w. faces "out" stlwrite('test.stl',fv) % Save to binary .stl Example 2: % Write ascii STL from gridded data [X,Y] = deal(1:40); % Create grid reference Z = peaks(40); % Create grid height stlwrite('test.stl',X,Y,Z,'mode','ascii') Example 3: % Write binary STL with coloured faces cVals = fv.vertices(fv.faces(:,1),3); % Colour by Z height. cLims = [min(cVals) max(cVals)]; % Transform height values nCols = 255; cMap = jet(nCols); % onto an 8-bit colour map fColsDbl = interp1(linspace(cLims(1),cLims(2),nCols),cMap,cVals); fCols8bit = fColsDbl*255; % Pass cols in 8bit (0-255) RGB triplets stlwrite('testCol.stl',fv,'FaceColor',fCols8bit)

I need to thank Duane Hanselman for suggesting this great idea.Fminspleas is a simple nonlinear least squares tool that fits regression models of the formY = a1*f1(X,C) + a2*f2(X,C) + ... + an*fn(X,C)X can be any array, so it works on multidimensional problems, and C is the set of only intrinsically nonlinear parameters. f1, f2, etc., must return a column vector result, of the same length as Y.Because the optimization (in this case, fminsearch) need only work on the intrinsically nonlinear parameters, far fewer function evaluations are required. The example I give in the help took only 32 function evaluations to estimate 2 linear parameters plus 1 nonlinear parameter, versus over 300 evaluations had I just called fminsearch directly.Fminspleas now allows you to specify bound constraints on the nonlinear parameters only. I'll see about adding linear parameter constraints if there are requests.Finally, fminspleas allows the user to supply a set of non-negative weights to the regression.E-mail me with any problems or bugs.

This is a simple interactive tool to help develop regular expressions. It lets you interactively write regular expressions and see REGEXP's outputs update as you type.The tool consists of just one M-file which creates a figure containing two edit-boxes (for the parse string and a regular expression string) and that displays all of REGEXP's outputs inside the figure (note that the column widths can be adjusted manually).This function can be used in two ways (and in any combination of these two ways):1. interactively by typing directly into the figure's edit-boxes, or2. by calling the function with exactly the same inputs and options as REGEXP itself.Simply keep the figure open to use any combination of these two modes of operation: this allows for refining of the regular expression by changing the parse and regular expression strings, and also updating any REGEXP options that are supplied as function inputs. Text can be copied and pasted both to and from the two edit-boxes. If required, REGEXP's output values can be returned by calling the function with the appropriate output specifiers (by default there are no function outputs).### Keep It Simple ###This is intended to be the simplest interactive regular expression tool on FEX: no highlighting, no links, no colors, no buttons, no java code, no file parsing, no apps to install, no third-party dependencies... just this one M-file is all you need. IREGEXP aids fast development of a regular expression, especially by allowing editing using only the keyboard (use the tab key to switch between the edit-boxes), to parse short pieces of text.### Important ###MATLAB's UICONTROL text edit-boxes do not update as you type, so I used a little keypress-hack to try and achieve this. This hack does get easily confused, so to ensure that the correct text is being parsed you will need to enter the text properly: clicking away from the edit-box, as per MATLAB's UICONTROL documentation, is the only way to guarantee this!Also note that in multiline mode the edit-box itself removes trailing newline characters from the text (not my code!).### Example ###Ellipses indicate continuation without closing the figure window.% Call with the default parse and regular expression strings:>> iregexp()% ...interactively add the parse string '0_AAA111-BB22.CCCC3'.% ...interactively add the regular expression '([A-Z]+)'.% ...call to set a new parse string:>> iregexp('0_aaa111-BB22.cccc3',[])% ...interactively change the regular expression to '([a-z]+)\d+'.% ...call to allow case-insensitive matching:>> iregexp([],[],'ignorecase')% ...interactively change the regular expression to '(?[A-Z]+)(?\d+)'.% ...call to assign selected outputs to some variables:>> [A,B,C,D] = iregexp([],[],'ignorecase','match','start','tokens','split') A = {'aaa111', 'BB22', 'cccc3'} B = [3, 10, 15] C = {{'aaa','111'},{'BB','22'},{'cccc','3'}} D = {'0_','-','.',''}

In addition to the STLREAD import function, this submission also includes a small demo that loads an STL model of a human femur bone.FV = STLREAD(FILENAME) imports triangular faces from the binary STL fileindicated by FILENAME, and returns the patch struct FV, with fields 'faces'and 'vertices'.[F,V] = STLREAD(FILENAME) returns the faces F and vertices V separately.[F,V,N] = STLREAD(FILENAME) also returns the face normal vectors.The faces and vertices are arranged in the format used by the PATCH plotobject.

PLOTCUBE - Display a 3D-cube in the current axes PLOTCUBE(EDGES,ORIGIN,ALPHA,COLOR) displays a 3D-cube in the current axes with the following properties: * EDGES : 3-elements vector that defines the length of cube edges * ORIGIN: 3-elements vector that defines the start point of the cube * ALPHA : scalar that defines the transparency of the cube faces (from 0 to 1) * COLOR : 3-elements vector that defines the faces color of the cubeExample: >> plotcube([5 5 5],[ 2 2 2],.8,[1 0 0]); >> plotcube([5 5 5],[10 10 10],.8,[0 1 0]); >> plotcube([5 5 5],[20 20 20],.8,[0 0 1]);

Sentence parsing can be done one word at a time using strtok. However, sometimes it is useful to (efficiently) extract all words into a cell array in one function call. The function allwords.m does exactly this.Spaces, white space (tabs), carriage returns, and punctuation characters are all valid separator characters by default. In this example, I had a period at the end, as well as multiple spaces between some words.str = 'The quick brown fox jumped over the lazy dog.';words = allwords(str)words = 'The' 'quick' 'brown' 'fox' 'jumped' 'over' 'the' 'lazy' 'dog' This utility can also work on any integer vector. The default separators for numeric vectors are [-inf inf NaN], but you can assign any separators you desire. Here, parse a string of integers, with only NaN elements as the separator.str = [1 2 4 2 inf 3 3 5 nan 4 6 5];words = allwords(str,nan);words{1}ans = 1 2 4 2 Inf 3 3 5words{2}ans = 4 6 5 Finally, allwords is efficient. For example, on a random numeric string of length 1e6, allwords parses it into over 90000 distinct "words" in less than 0.5 seconds.str = round(rand(1,1000000)*10);ticwords = allwords(str,[0 10]);tocElapsed time is 0.455194 seconds. There were over 90000 different words that were extractednumel(words)ans = 90310 The longest word had length 104.max(cellfun(@numel,words))ans = 104

This code increases the speed of the xlswrite function when used in loops or multiple times. The problem with the original function is that it opens and closes the Excel server every time the function is used. To increase the speed I have just edited the original function by removing the server open and close function from the xlswrite function and moved them outside of the function. To use this first run the following code which opens the activex server and checks to see if the file already exists (creates if it doesnt):Excel = actxserver ('Excel.Application');File='C:\YourFileFolder\FileName';if ~exist(File,'file') ExcelWorkbook = Excel.workbooks.Add; ExcelWorkbook.SaveAs(File,1); ExcelWorkbook.Close(false);endinvoke(Excel.Workbooks,'Open',File);Then run the new xlswrite1 function as many times as needed or in a loop (for example xlswrite1(File,data,location). Then run the following code to close the activex server:invoke(Excel.ActiveWorkbook,'Save');Excel.QuitExcel.deleteclear ExcelThis works exactly like the original xlswrite function, only many many times faster.

Subplot tends to leave a lot of empty space around the axes. Tight_subplot allows to adjust the spacing between the axes as well as the margins around the axes.For example:[ha, pos] = tight_subplot(3,2,[.01 .03],[.1 .01],[.01 .01])for ii = 1:6; axes(ha(ii)); plot(randn(10,ii)); endset(ha(1:4),'XTickLabel',''); set(ha,'YTickLabel','')

This function makes it easy to display a mesh directly above a grayscale image. The mesh can use any colormap and can be at variable heights above the image. The example, which requires the IPT, is the screenshot.help meshCanopy function meshCanopy: display a mesh above a grayscale image SCd 11/18/2010 Updates: -11/22/2010: Added example (requires IPT) Added height input argument Input Arguments: -I: 2-dimensional grayscale image slice. The values are expected to range from 0 to 255. If the maximum value is greater than 255 or the minimum value is less than 0, it will be scaled to 0:255. Else it will remain unchanged. -Mdata: 2-dimensional mesh data (Z for a meshplot). NOTE: the mesh command will be called with: >>[ii jj] = meshgrid(ceil(cumsum(diff([0 linspace(1,size(I,2),size(Mdata,2))]))),ceil(cumsum(diff([0 linspace(1,size(I,1),size(Mdata,1))])))); >>mesh(ii,jj,Mdata); and thus does not need to be the same size as the image! -Mmap: string, function_handle or nx3, mesh color map. See: >>doc colormap for valid options. The argument is optional and defaults to 'jet' Examples: 'jet', @jet, [0 0 1; 0.5 0;.1 .1 .1] -height: scalar height of the mesh above the image so you can see both. Optional defaults to 80. Output Arguments: -None! Example: (Requires the Image Processing Toolbox) %Display a Mesh Canopy of a standard deviation image, above the original image I = imread('cameraman.tif'); M = stdfilt(I); meshCanopy(I,M,@spring) See also: mesh colormap

Convert an xml file into a MATLAB structure for easy access to the data.

UniqueFuncNames - Check uniqueness of function namesIf you install a large 3rd party toolbox, the file names may interfere with other installed toolboxes. This simple funtion compares the names of all M-, P- and Mex-files found in the Matlab path and displays non-unique names.P- and Mex-files with the same name as a corresponding M-file are accepted, if they are found in the same folder.Local subfunctions inside the M- or P-file and nested functions are not taken into account, because it is assumed, that a potential shadowing is wanted.Class paths as "\@cell" and package paths as "\+mypackage" are not considered in this version.INPUT: None.OUTPUT: Logical flag, TRUE if the names are unique considering some exceptions: 1. Files which are intentionally not unique: "Contents.m" exists in each folder. "prefspanel.m" exists in some folder to register control panels. "messageProductNameKey" returns the product key for toolboxes. 2. Some user defined folders might contain functions, which are wanted to shadow function of Matlab's or user define toolbox functions, e.g. to improve them. Such folders must be inserted in a leading position in the Matlab path. A further example is a folder, which contains Mex functions, which are compiled for a specific Matlab version, e.g. if you run Matlab 6.5 (DLL) and 7 (MEXW32) simulataneously. 3. Further exceptions occur e.g. in Matlab 2009a: \R2009a\toolbox\matlab\lang\function.m \R2009a\toolbox\compiler\function.m Exclude one of them using the full file name including the path. The exceptions depend on your installed toolboxes and have to be adjusted to your machine. The corresponding lines are marked by '###' in the source.I'd appreciate all comments and ideas for improvements and additions. For further debugging see also: CHECKVARS (Matt Fig): http://www.mathworks.com/matlabcentral/fileexchange/27853FDEP (Us): http://www.mathworks.com/matlabcentral/fileexchange/17291

Natural order sorting sorts strings containing digits in a way such that the numerical value of the digits is taken into account. It is especially useful for sorting file names containing index numbers with different numbers of digits. Often, people will use leading zeros to get the right sort order, but with this function you don't have to do that. For example, with input of{'file1.txt','file2.txt','file10.txt'}a normal sort will give you{'file1.txt','file10.txt','file2.txt'} whereas, sort_nat will give you{'file1.txt','file2.txt','file10.txt'}

permn - permutations with repetition Using two input variables V and N, M = permn(V,N) returns all permutations of N elements taken from the vector V, with repetitions. V can be any type of array (numbers, cells etc.) and M will be of the same type as V. If V is empty or N is 0, M will be empty. M has the size numel(V).^N-by-N. When only a subset of these permutations is needed, you can call permn with 3 input variables: M = permn(V,N,K) returns only the K-ths permutations. The output is the same as M = permn(V,N) ; M = M(K,:), but it avoids memory issues that may occur when there are too many combinations. This is particulary useful when you only need a few permutations at a given time. If V or K is empty, or N is zero, M will be empty. M has the size numel(K)-by-N. [M, I] = permn(...) also returns an index matrix I so that M = V(I). Examples: M = permn([1 2 3],2) % returns the 9-by-2 matrix: 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 M = permn([99 7],4) % returns the 16-by-4 matrix: 99 99 99 99 99 99 99 7 99 99 7 99 99 99 7 7 ... 7 7 7 99 7 7 7 7 M = permn({'hello!' 1:3},2) % returns the 4-by-2 cell array 'hello!' 'hello!' 'hello!' [1x3 double] [1x3 double] 'hello!' [1x3 double] [1x3 double] V = 11:15, N = 3, K = [2 124 21 99] M = permn(V, N, K) % returns the 4-by-3 matrix: % 11 11 12 % 15 15 14 % 11 15 11 % 14 15 14 % which are the 2nd, 124th, 21st and 99th permutations % Check with permn using two inputs M2 = permn(V,N) ; isequal(M2(K,:),M) % Note that M2 is a 125-by-3 matrix % permn can be used generate a binary table, as in B = permn([0 1],5) NB Matrix sizes increases exponentially at rate (n^N)*N. See also perms, nchoosek allcomb, permpos on the File Exchange

TRICONTOUR(TRI,X,Y,Z,N) draws scalar N contour lines treating the values in Z as heights above a plane. TRI,X,Y,and Z define a triangulation where the triangles are defined by the M-by-3 face matrix TRI, such as that returned by DELAUNAY. Each row of TRI contains indices into the X,Y, and Z vertex vectors to define a single triangular face. Contours are computed directly from the triangulation rather than interpolating back to a cartesian grid using GRIDDATA.TRICONTOUR(TRI,X,Y,Z,V) draws length(V) contour lines at the values specified in vector V.TRICONTOUR(TRI,X,Y,Z,[v v]) draws a single contour line at the level v.[C,H] = TRICONTOUR(...) returns contour matrix C as described in CONTOURC and a vector of handles H to the created patch objects.H can be used to set patch properties.CLABEL(C) or CLABEL(C,H) labels the contour levels.

RANDRAWEFFICIENT RANDOM VARIATES GENERATOR (from over 50 distributions):Alpha, Anglit, Antilognormal,Arcsin,Bernoulli, Bessel, Beta, Binomial, Bradford, Burr, Cauchy, Chi, Chi-Square (Non-Central), Chi-Square (Central), Cobb-Douglas, Cosine, Double-Exponential, Erlang, Exponential, Extreme-Value, F (Central), F (Non-Central), Fisher-Tippett, Fisk, Frechet, Furry, Gamma, Generalized Inverse Gaussian, Generalized Hyperbolic, Geometric, Gompertz, Gumbel, Half-Cosine, Hyperbolic Secant, Hypergeometric, Inverse Gaussian, Laplace, Logistic, Lognormal, Lomax, Lorentz, Maxwell,Nakagami, Negative Binomial, Normal, Normal-Inverse-Gaussian (NIG),Pareto, Pareto2, Pascal, Planck, Poisson, Quadratic, Rademacher, Rayleigh,Rice, Semicircle, Skellam, Student's-t, Triangular, Truncated Normal, Tukey-Lambda, U-shape, Uniform (continuous), Von Mises, Wald, Weibull, Wigner Semicircle, Yule, Zeta, Zipf

There are several utilities around to compute interpoint distances, but none of them did fully what I thought important. What were my goals?1. Inter-point distances are sometimes computed within one set of points, or between two sets. So a tool must handle either case.2. Efficiency is important, but a common method for inter-point (Euclidean) distances uses a trick that results in a loss of accuracy. The good thing is bsxfun allows us to compute distances both efficiently and accurately.3. Many times we wish to compute an inter-point, but we only need some subset of the entire matrix. Then it might be nice to have a list of only the single nearest neighbor for each point in our set, or only the large or small distances beyond some limit.4. Where appropriate, a sparse distance matrix might be useful.5. Really large problems can sometimes be solved by breaking the problem into smaller chunks. IPDM does this where appropriate.6. There are many special cases that can be solved efficiently. For example, to find the nearest neighbor for one dimensional data is a simple thing, costing no more than a sort. One does not need to compute all distances if only the closest point is of interest. (There are several other special cases that can be sped up, perhaps using k-d trees, or other algorithms. If interest is seen I'll try to provide them.)All of these things and more are satisfied by IPDM. It uses a property/value pair interface to specify the options.Find the nearest neighbors in 1-dimensional data:A = randn(10000,1);B = randn(15000,1);tic,d=ipdm(A,B,'subset','nearest');tocElapsed time is 0.151346 seconds.A note to those who might be worried about absolute speed on small sets of data. I've now considerably sped up the code for simple calls, reducing the basic overhead by a factor of roughly 4.See the demo file for many examples of use.

This is a GUI application that allows multiple files or directories to be selected and allows you to manage the list (remove files, reorder, etc.) before returning. It has basic filtering as well as regular expression filtering and navigation of the file system is easy. The output is configurable (cell, struct or char arrays). It is written entirely in M and so is platform independent.

POLYPARCI uses the procedures outlined in the ‘polyfit’ documentation to calculate the covariance matrix, and uses ‘betainc’ and ‘fzero’ to calculate the cumulative t-distribution and the inverse t-distribution for a given probability and degrees-of-freedom. It uses only core MATLAB functions and does not require the Statistics Toolbox. The t-distribution and t-statistic calculations have a relative error of about 1E-012 compared to the Statistics Toolbox functions ‘tcdf’ and ‘tinv’. The relative error of the confidence intervals is about 1E-005 compared to those calculated by ‘nlinfit’ and ‘nlparci’ with the same model on the same data.

An update to Joe Conti's popular vol3d function, allowing voxel colors and alpha values to be defined explicitly. Functionality is increased, but the function is entirely backwards compatible.In cases where voxels can be any RGB color, use: vol3d('CData', cdata);where cdata is an MxNxPx3 array, with RGB color along the 4th dimension. In cases where color and alpha values are highly independent, specify an MxNxP alphamatte as follows: vol3d('CData', cdata, 'Alpha', alpha);This function amends the original (as little as possible) with the full permission of Joe Conti. The original function, which came with some additional tools for editing colormaps and alphamaps, is sadly no longer available.The way this rendering approach works is to render the six sides of each voxel as a translucent plane.

The money changing problem is a simple one to state. For example, how many different ways can one form change of a dollar (100 cents) by using only coins of denomination [1 5 10 25 50] ? (The answer is 292.)Its an example of a general problem, i.e., in how many unique ways can an integer be partitioned as a sum of smaller positive integers?http://en.wikipedia.org/wiki/Integer_partitionI wrote partitions to solve the fully general problem, but it can be used with restrictions too. You can constrain the set of elements in the sum, and the maximum number of times any one elements can appear, as well as fixing the total number of terms that will appear in the final sum.See the demo for a few examples of use.

SURF2STL Write STL file from surface data. SURF2STL('filename',X,Y,Z) writes a stereolithography (STL) file for a surface with geometry defined by three matrix arguments, X, Y and Z. X, Y and Z must be two-dimensional arrays with the same size. SURF2STL('filename',x,y,Z), uses two vector arguments replacing the first two matrix arguments, which must have length(x) = n and length(y) = m where [m,n] = size(Z). Note that x corresponds to the columns of Z and y corresponds to the rows. SURF2STL('filename',dx,dy,Z) uses scalar values of dx and dy to specify the x and y spacing between grid points. SURF2STL(...,'mode') may be used to specify the output format. 'binary' - writes in STL binary format (default) 'ascii' - writes in STL ASCII format Example: surf2stl('test.stl',1,1,peaks); See also SURF. Author: Bill McDonald, 02-20-04

VIDEOFIG(NUM_FRAMES, @REDRAW_FUNC) creates a figure with a horizontal scrollbar and shortcuts to scroll automatically. The scroll range is 1 to NUM_FRAMES. The function REDRAW_FUNC(F) is called to redraw at scroll position F (for example, REDRAW_FUNC can show the frame F of a video).This can be used not only to play and analyze standard videos, but it also lets you place any custom Matlab plots and graphics on top.Jiro posted a great example on the Pick of the Week blog, along with a nice GIF animation so you can see it in motion:http://blogs.mathworks.com/pick/2010/12/10/video-player-for-your-frame-based-processing/ EXAMPLE 1Place this in a file called "redraw.m": function redraw(frame) imshow(['AT3_1m4_' num2str(frame, '%02.0f') '.tif']) end Then from a script or the command line, call: videofig(10, @redraw); redraw(1) The images "AT3_1m4_01.tif" ... "AT3_1m4_10.tif" are part of the ImageProcessing Toolbox and there's no need to download them elsewhere. EXAMPLE 2Change the redraw function to visualize the contour of a single cell: function redraw(frame) im = imread(['AT3_1m4_' num2str(frame, '%02.0f') '.tif']); slice = im(210:310, 210:340); [ys, xs] = find(slice < 50 | slice > 100); pos = 210 + median([xs, ys]); siz = 3.5 * std([xs, ys]); imshow(im), hold on rectangle('Position',[pos - siz/2, siz], 'EdgeColor','g', 'Curvature',[1, 1]) hold off end The keyboard shortcuts are: Enter (Return) -- play/pause video (25 frames-per-second default). Backspace -- play/pause video 5 times slower. Right/left arrow keys -- advance/go back one frame. Page down/page up -- advance/go back 30 frames. Home/end -- go to first/last frame of video. See HELP VIDEOFIG for more options.

[B, IDX, OUTLIERS] = DELETEOUTLIERS(A, ALPHA, REP) For input vector A, returns a vector B with outliers (at the significance level alpha) removed. Also, optional output argument idx returns the indices in A of outlier values. Optional output argument outliers returns the outlying values in A. ALPHA is the significance level for determination of outliers. If not provided, alpha defaults to 0.05. REP is an optional argument that forces the replacement of removed elements with NaNs to preserve the length of a. (Thanks for the suggestion, Urs.) This is an iterative implementation of the Grubbs Test that tests one value at a time. In any given iteration, the tested value is either the highest value, or the lowest, and is the value that is furthest from the sample mean. Infinite elements are discarded if rep is 0, or replaced with NaNs if rep is 1 (thanks again, Urs). Appropriate application of the test requires that data can be reasonably approximated by a normal distribution. For reference, see:1) "Procedures for Detecting Outlying Observations in Samples," by F.E. Grubbs; Technometrics, 11-1:1--21; Feb., 1969, and 2) _Outliers in Statistical Data_, by V. Barnett and T. Lewis; Wiley Series in Probability and Mathematical Statistics;John Wiley & Sons; Chichester, 1994.A good online discussion of the test is also given in NIST's Engineering Statistics Handbook: http://www.itl.nist.gov/div898/handbook/eda/section3/eda35h.htm ex:[B,idx,outliers] = deleteoutliers([1.1 1.3 0.9 1.2 -6.4 1.2 0.94 4.2 1.3 1.0 6.8 1.3 1.2], 0.05)returns:B = 1.1000 1.3000 0.9000 1.2000 1.2000 0.9400 1.3000 1.0000 1.3000 1.2000idx = 5 8 11outliers = -6.4000 4.2000 6.8000 ex:B = deleteoutliers([1.1 1.3 0.9 1.2 -6.4 1.2 0.94 4.2 1.3 1.0 6.8 1.3 1.2 Inf 1.2 -Inf 1.1], 0.05, 1)returns:B = 1.1000 1.3000 0.9000 1.2000 NaN 1.2000 0.9400 NaN 1.3000 1.0000 NaN 1.3000 1.2000 NaN 1.2000 NaN 1.1000 Written by Brett Shoelson, Ph.D.brett.shoelson@mathworks.com9/10/03Modified 9/23/03 to address suggestions by Urs Schwartz.Modified 10/08/03 to avoid errors caused by duplicate "maxvals."(Thanks to Valeri Makarov for modification suggestion.)

This function quickly finds local peaks or valleys (local extrema) in a noisy vector using a user defined magnitude threshold to determine if each peak is significantly larger (or smaller) than the data around it. The problem with the strictly derivative based peak finding algorithms is that if the signal is noisy many spurious peaks are found. However, more complex methods often take much longer for large data sets, require a large amount of user interaction, and still give highly variable results.This function attempts to use the alternating nature of the derivatives along with the user defined threshold to identify local maxima or minima in a vector quickly and robustly. The function is able to correctly identify the major peaks on a 1.5 million data point noisy sum of sinusoids in under a second as is shown in the example in the code comments.Please don't hesitate to comment or contact me if you have suggestions about improvements that could be made to this function.

ARROW (5/12/2021) Draw a line with an arrowhead.ARROW(Start,Stop) draws a line with an arrow from Start to Stop (points should be vectors of length 2 or 3, or matrices with 2 or 3 columns), and returns the graphics handle of the arrow(s). By itself, ARROW will use the mouse to allow selection.ARROW DEMO & ARROW DEMO2 show 3-D & 2-D demos of the capabilities of ARROW.ARROW PROPERTIES shows the properties that can be set (length, base angle, tip angle, width, which ends have arrowheads, etc.)

This function provides all combinations of integer vector that must verify a criteria on the sum.Supported criteria issum(v) == L1sum(v) <= L1sum(v) < L1

This exciting tool with a small footprint run-length- decodes and encodes any MATLAB data type including- numbers- strings- cells with any contentsin almost no timelook at the accompanying published m-file for a few persuasive examples

When plotting a set of lines, you may want to distinguish them by color. By default, Matlab chooses a small set of colors and cycles among them, and so if you have more than a few lines there will be confusion about which line is which. To fix this problem, one would want to be able to pick a much larger set of distinct colors, where the number of colors equals or exceeds the number of lines you want to plot. Because our ability to distinguish among colors has limits, one should choose these colors to be "maximally perceptually distinguishable."This function generates a set of colors which are distinguishable by reference to the "Lab" color space, which more closely matches human color perception than RGB. Given an initial large list of possible colors, it iteratively chooses the entry in the list that is farthest (in Lab space) from all previously-chosen entries.

Function calculates intersection of any two triangulated surfaces using triangle/triangle intersection algorithm proposed by Tomas Möller (1997) and implemented as highly vectorized MATLAB code. The algorithm was expanded to include calculation of the intersection surface, in addition to boolean matrix cataloging which triangle from one surface intersects with which triangle in the other surface. Function can be used for contour line calculations and can handle surfaces residing on the same plane.

MAT = NPERMUTEK(N,K) returns all possible permutations of the elements taken from vector N of length K. This type of sampling is an ordered sample with replacement.This is also known as the permutations with repetition. MAT has size (length(N)^K)-by-K, where K must be a scalar. [MAT, IDX] = NPERMUTEK(N,K) also returns IDX such that MAT = N(IDX).If N is of class single, MAT and IDX will be also.Please email me about bugs in the code.Thanks

Use the outputs from any of the contour plot functions to produce a table of (x,y) coordinates of the contour lines organized by contour level and group. [cm, h] = contour(___);contourTable = getContourLineCoordinates(cm);--or-- contourTable = getContourLineCoordinates(h);contourTable = Level.........Group..........X............Y ____________________________________ -5.8504.........1..........0.44266....-1.75 -5.8504.........1..........0.375........-1.8038 -5.8504.........1..........0.25..........-1.8526 -5.8504.........1..........0.125........-1.8498 etc....Where Level is the contour level in the LevelList of a contour object, Group is a grouping variable for contour levels, and (X,Y) are coordinates along the contour lines.

For a vector V, I = runindex(V) returns a vector I of the same size as V with linear indices per run within V. Runs are contiguous sequences of one value for one or more consecutive elements in V. Example: % create a vector with four runs: 3x20, 2x4, 4x55, 1x999 V = [20 20 20 4 4 55 55 55 55 999] I = runindex(V) % [ 1 2 3 1 2 1 2 3 4 1] [I, RLE] = rundindex(V) also returns a run length encoding of V in the N-by-3 array RLE. Each row is a run, with the value in the first column, the start index in the second column, and the run length in the third column. N is the number of runs. V = [8 7 7 7 3 3 12 12 12 12] [~, RLE] = runindex(V) % RLE = % 8 1 1 % 7 2 3 % 3 5 2 % 12 7 4 When given two input vectors U and C, V = runindex(U, C) decodes the vectors U (values) and C (counts) into the vector V. V is the concatenation of all values of U, where the k-th value U(k) is repeated C(k) times. V is a sum(C)-by-1 column vector. When C(k) is 0, U(k) is omitted from the vector. [V, RLE] = runindex(U, C) returns the run-length encoding of V in RLE. V = runindex([5 10 99], [2 1 3]) % V = [5 5 10 99 99 99] Vin = [1 1 2 2 1 1 1] [I, RLE] = runindex(Vin) % encoding % I = [1 2 1 2 1 2 3] Vout = runindex(RLE(:,1), RLE(:,3)) % decoding % Vout equals Vin V = runindex([0 1 0 2], [2 3 1 4]) % V = [0 0 1 1 1 0 2 2 2 2]) ; See also cumsum, diff, find Notes - This function is related to run-length encoding: https://en.wikipedia.org/wiki/Run-length_encoding

This tool saves your covariance matrices, turning them into something that really does have the property you will need. That is, when you are trying to use a covariance matrix in a tool like mvnrnd, it makes no sense if your matrix is not positive definite. So mvnrnd will fail in that case.But sometimes, it appears that users end up with matrices that are NOT symmetric and positive definite (commonly abbreviated as SPD) and they still wish to use them to generate random numbers, often in a tool like mvnrnd. A solution is to find the NEAREST matrix (minimizing the Frobenius norm of the difference) that has the desired property of being SPD.I see the question come up every once in a while, so I looked in the file exchange to see what is up there. All I found was nearest_posdef. While this usually almost works, it could be better. It actually failed completely on most of my test cases, and it was not as fast as I would like, using an optimization. In fact, in the comments to nearest_posdef, a logical alternative was posed. That alternative too has its failures, so I wrote nearestSPD, partly based on what I found in the work of Nick Higham.nearestSPD works on any matrix, and it is reasonably fast. As a test, randn generates a matrix that is not symmetric nor is it at all positive definite in general.U = randn(100);nearestSPD will be able to convert U into something that is indeed SPD, and for a 100 by 100 matrix, do it quickly enough.tic,Uj = nearestSPD(U);tocElapsed time is 0.008964 seconds.The ultimate test of course, is to use chol. If chol returns a second argument that is zero, then MATLAB (and mvnrnd) will be happy![R,p] = chol(Uj);pp = 0

PLOTYYY builds upon plotyy to include a third y-axis. It also provides an easy way of labelling all three y-axes at once.

This function uses MATLAB's INTEGRAL2 and INTEGRAL3 functions iteratively to perform integrals of order 4, 5, and 6.

Y = INPAINTN(X) replaces the missing data in X by extra/interpolating the non-missing elements. The non finite values (NaN or Inf) in X are considered as missing data. X can be any N-D array.Type "help inpaintn" in the Matlab command windows for several examples.INPAINTN (no input/output argument) runs a 3-D example. Important note:----------------INPAINTN uses an iterative process that converges toward the solution. Y = INPAINTN(X,N) uses N iterations. By default, N = 100. If you estimate that INPAINTN did not totally converge, then increase N: Y = INPAINTN(X,1000);----- When using this algorithm, please refer to these 2 papers:1) Garcia D. Robust smoothing of gridded data in one and higher dimensions with missing values. Comput Statist Data Anal, 2010;54:1167-1178 http://www.biomecardio.com/publis/csda10.pdf2) Wang G, Garcia D et al. A three- dimensional gap filling method for large geophysical datasets: Application to global satellite soil moisture observations.Environ Modell Softw, 2012;30:139-142.http://www.biomecardio.com/publis/envirmodellsoftw12.pdf.pdf -----A series of examples is available here:http://www.biomecardio.com/matlab/inpaintn_doc.html Example:--------%% ---- 2-D data ---- %%n = 256;y0 = peaks(n);y = y0;I = randperm(n^2);y(I(1:n^2*0.5)) = NaN; % lose 1/2 of datay(40:90,140:190) = NaN; % create a holez = inpaintn(y,200); % inpaint datasubplot(2,2,1:2), imagesc(y), axis equal offtitle('Corrupt data')subplot(223), imagesc(z), axis equal offtitle('Recovered data ...')subplot(224), imagesc(y0), axis equal offtitle('... compared with original data')------http://www.biomecardio.com-----

GETUNDOC('OBJECT') or GETUNDOC(H) returns a structure of undocumented properties (names & values) for the object having handle H or identified by the string 'OBJECT'.GETUNDOC(H,true) returns the undocumented properties of H, while skipping the following standard undocumented properties: ALimInclude, ApplicationData, Behavior, CLimInclude, HelpTopicKey, IncludeRenderer, PixelBounds, Serializable, XLimInclude, YLimInclude, ZLimIncludeFor example, GETUNDOC('axes') or GETUNDOC(gca) returns undocumented property names and values for the axes object.Full technical description: http://UndocumentedMatlab.com/blog/getundoc-get-undocumented-object-properties/This is an extension of Duane Hanselman's original utility from 2006 (which is no longer available on the File Exchange).

This function downsamples 1D or 3D data to monthly, yearly, hourly, minutely, or secondly data. This function was originally designed to create monthly mean time series from daily geospatial climate data.SyntaxZ_downsamp = downsample_ts(Z,t)Z_downsamp = downsample_ts(...,'DownsamplingPeriod')Z_downsamp = downsample_ts(...,'function')[Z_downsamp,t_downsamp] = downsample_ts(...)DescriptionZ_downsamp = downsample_ts(Z,t) downsamples Z, which must be provided with a corresponding time vector t. Z can be 1D if its length matches the length of t. If Z is three-dimensional, the length of its third dimension must match the length of t. For geospatial climate data arrays, dimensions of Z might correspond to lat x lon x time or lon x lat x time.Z_downsamp = downsample_ts(...,'DownsamplingPeriod') specifies a downsampling period as 'year' 'month' (default) 'day' 'hour' 'minute' 'second'Z_downsamp = downsample_ts(...,'function') specifies a function to perform on the data. By default, monthly averages are taken, but you may wish to return the monthly median or monthly standard deviation or any of the functions listed below.A note on functions which ignore NaNs: To get the monthly means of data while ignoring NaN values, you can use the 'nanmean' option. The nanmean function is part of the Statistics Toolbox, but may also be found as part of the NaN Suite on File Exchange. However, the File Exchange versions mix up the order of dimensions and flags for nanstd, nanvar, nanmin, and nanmax, so you will need the Statistics Toolbox for those particular functions. In all, the following functions are available: 'mean' (default) 'nanmean' ignores NaN values in Z. Requires Statistics toolbox or NaN Suite. 'median' 'nanmedian' ignores NaN values in Z. Requires Statistics toolbox or NaN Suite. 'min' 'nanmin' ignores NaN values in Z. Requires Statistics toolbox. 'max' 'nanmax' ignores NaN values in Z. Requires Statistics toolbox. 'std' standard deviation. 'nanstd' ignores NaN values in Z. Requires Statistics toolbox. 'var' variance. 'nanvar' ignores NaN values in Z. Requires Statistics toolbox. 'mode' 'sum' 'nansum'[Z_downsamp,t_downsamp] = downsample_ts(...) also returns a time array corresponding to Z_downsamp. If Z is 3D or, t_downsamp corresponds to the third dimension of Z_downsamp. Each value in t_downsamp represents the mean time of all data contributing to that slice of Z_downsamp.

UNINIT is very similar to the ZEROS function, except that UNINIT returns an uninitialized array instead of a zero-filled array. Thus, UNINIT is faster than the ZEROS function for large size arrays. Since the return variable is uninitialized, the user must take care to assign values to the elements before using them. UNINIT is useful for preallocation of an array where you know the elements will be assigned values before using them.Syntax (nearly identical to the ZEROS function) B = uninit B = uninit(n) B = uninit(m,n) B = uninit([m n]) B = uninit(m,n,p,...) B = uninit([m n p ...]) B = uninit(size(A)) B = uninit(m, n,...,classname) B = uninit([m,n,...],classname) B = uninit(m, n,...,complexity) B = uninit([m,n,...],complexity) B = uninit(m, n,...,classname,complexity) B = uninit([m,n,...],classname,complexity) Description B = uninit Returns a 1-by-1 scalar uninitialized value. B = uninit(n) Returns an n-by-n matrix of uninitialized values. An error message appears if n is not a scalar. B = uninit(m,n) or B = uninit([m n]) Returns an m-by-n matrix of uninitialized values. B = uninit(m,n,p,...) or B = uninit([m n p ...]) Returns an m-by-n-by-p-by-... array of uninitialized values. The size inputs m, n, p, ... should be nonnegative integers. Negative integers are treated as 0. B = uninit(size(A)) Returns an array the same size as A consisting of all uninitialized values. If any of the numeric size inputs are empty, they are taken to be 0. The optional classname argument can be used with any of the above. classname is a string specifying the data type of the output. classname can have the following values: 'double', 'single', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64', 'logical', or 'char'. (Note: 'logical' and 'char' are not allowed in the ZEROS function) The default classname is 'double'. The optional complexity argument can be used with any of the above. complexity can be 'real' or 'complex', except that 'logical' and 'char' outputs cannot be complex. (this option not allowed in the ZEROS function) The default complexity is 'real'.UNINIT is typically self building. That is, the first time you call UNINIT, the uninit.m file recognizes that the mex routine needs to be compiled and then the compilation will happen automatically. UNINIT uses the undocumented MATLAB API function mxCreateUninitNumericMatrix. It has been tested in PC WinXP versions R2006b through R2011a, but may not work in future versions or non-PC versions of MATLAB.

This script is a demo that shows you how to find objects of a certain color in an image. For this example I'm using the standard onion, peppers, or kids image that ships with the Image Processing Toolbox. You can also select one of your own color images instead if you wish. Then I separate the image into its component hue, saturation, and value color bands. I ask you what color you want to find (red, green, yellow, white). I compute thresholds, and ultimately find a mask for the regions of the color you specified. Prompts will guide you through the demo step by step. I multiply this mask by the original image to show the image with only the requested color showing and everything else blacked out.If you want to do any measurements of the objects, I refer you to my blob measurement demo file at http://www.mathworks.com/matlabcentral/fileexchange/25157Requires the Image Processing Toolbox. Tested with MATLAB release R2014a.

Structures are a convenient way of carrying around many variables as a single object and of passing those variables to a function packed in a single argument.Once a structure has been passed to a function, however, many users (according to various Newsgroup posts) find it tiresome to have to access its fields repeatedly through dot-indexing notation and have sought automated ways to take a structure and assign all of its fields to separate variables, as ina = myStruct.a; b = myStruct.b; c = myStruct.c; etc...Solutions based on assignin() have often been tried, but are hazardous, for reasons discussed, for example, in this thread:http://www.mathworks.com/matlabcentral/newsreader/view_thread/244639#628695The structvars() tool in this FEX submission does something virtually as good and far safer. Given a structure, it will print the lines of code needed to assign structure fields to separate variables (or the reverse). The lines of code can be conveniently copy/pasted from the command window to the file editor at the location in the file where the variables need to be unpacked. Examples: Given structure myStruct, with fields a,b,c, & d (1) structvars(myStruct) %assign fields to variables ans = a = myStruct.a; b = myStruct.b; c = myStruct.c; d = myStruct.d; (2) structvars(3,myStruct) %split the last result across 3 columns ans = a = myStruct.a; c = myStruct.c; d = myStruct.d; b = myStruct.b; (3) structvars(3,myStruct,0) %assign variables to fields ans = myStruct.a = a; myStruct.c = c; myStruct.d = d; myStruct.b = b; The commands can obviously be regenerated if you add/remove structure fields later on. On the other hand, the effort of just making these incremental edits manually is typically minimal.

CH = getkeywait(P) waits for a keypress for a maximum of P seconds. P should be a positive number. CH is a double representing the key pressed key as an ascii number, including backspace (8), space (32), enter (13), etc. If a non-ascii key (Ctrl, Alt, etc.) is pressed, CH will be NaN. If no key is pressed within P seconds, -1 is returned, and if something went wrong during excution 0 is returned. Without argument, getkeywait waits until a key is pressed. [CH, RT] = getkeywait(..) returns the response time in seconds in RT. Example: disp('Press a key within 5 seconds') ; [CH, DT] = getkeywait(5) See also input, ginput, waitbar, msgbox getkey (file Exchange)Authors note: This file was created in 2005 and is still working ;-)

I've seen many people ask for a way to find the closest point on a curve from some given point in space. If the curve is a piecewise linear one, this is not too difficult, since this reduces to finding the closest point on a line segment, and then testing each line segment. (With care, you need not test EVERY line segment.)For a cubic spline however, this becomes more difficult, but still doable in a mathematical sense without an explicit optimization. Not too much more than roots is necessary.Distance2curve allows you to specify a set of general points in an n-dimensional space as a connected space curve. A spline (or pchip) is then fit in terms of arc length along the curve, and the closest point identified.

ARROW3(P1,P2) draws lines from P1 to P2 with directional arrowheads. P1 and P2 are either nx2 or nx3 matrices. Each row of P1 is an initial point, and each row of P2 is a terminal point.ARROW3(P1,P2,S,W,H,IP,ALPHA,BETA) can be used to specify properties of the line, initial point marker, and arrowhead. Type "help arrow3" at the command prompt for more informationWhat's new in Version 5:All arrowhead and initial point marker sizes (W, H, and IP) are relative to the PlotBox diagonal.Version 5 attempts to preserve the appearance of existing axes. In particular, ARROW3 will not change XYZLim, View, or CameraViewAngle. ARROW3 does not, however, support stretch-to-fill scaling. If a particular aspect ratio or variable limit is required, use DASPECT, PBASPECT, AXIS, or XYZLIM commands before calling ARROW3. Users are encouraged to report problems directly to the author.

Demo to perform very, very simple color detection in LAB color space. The RGB image is converted to LAB color space and then the user draws some freehand-drawn irregularly shaped region to identify a color. The Delta E (the color difference in LAB color space) is then calculated for every pixel in the image between that pixel's color and the average LAB color of the drawn region. The user can then specify a number that says how close to that color would they like to be. The software will then find all pixels within that specified Delta E of the color of the drawn region.

A modified version of XTICKLABEL_ROTATE90, this version allows for arbitrary angle rotation and most importantly the use of text labels. In addition, an attempt is made to adjust the size and placement of the axis and xlabel to accommodate the new labels. Example : %Use text labels rotated 45° without tex interpreter boxplot(randn(5,5),1) xticklabel_rotate([1:5],45,{'label_1','label_2','label_3','label_4','label_5'},'interpreter','none')

CH = getkey waits for a single keypress and returns the ASCII code. It accepts all ascii characters, including backspace (8), space (32), enter (13), etc, that can be typed on the keyboard. Non-ascii keys (ctrl, alt, ..) return a NaN. CH is a double. CH = getkey(N) waits for N keypresses and returns their ASCII codes. getkey(1) is the same as getkey without arguments. getkey('non-ascii') or getkey(N, 'non-ascii') uses non-documented matlab features to return a string describing the key pressed. In this way, keys like ctrl, alt, tab etc. can also distinguished. The return is a string (when N = 1) or a cell array of strings. [CH, T] = getkey(...) also returns the time between the start of the function and each keypress. This is, however, not very accurate. This function is kind of a workaround for "getch" in C. It uses a modal, but non-visible window, which does show up in the taskbar. C-language keywords: KBHIT, KEYPRESS, getkey, GETCH Example 1 - get a single ascii key fprintf('\nPress any key: ') ; ch = getkey ; fprintf('%c\n',ch) ; Example 2 - wait for a specific key fprintf('\nPress the Ctrl-key within 3 presses: ') ; ch = getkey(3,'non-ascii') if ismember('control', ch), fprintf('OK\n') ; else fprintf(' ... wrong keys ...\n') ; end Example 3 - Typing game S = 'abcdefghjiklm' ; fprintf('Type "%s" as fast as possible ...\n', S) ; [C, T] = getkey(numel(S)) ; C = char(C) ; T = T(end)-T(1) ; if ~isequal(S, C), fprintf('OOPS!!! ') ; end fprintf('You typed "%s" in %.2f seconds.\n', C, T) ; See also input, uiwait getkeywait (file Exchange)Author's note: after 14 years still going strong ;-)

SpinCalc is a consolidated matlab function that will convert any rotation data between the 4 types included. Will also convert between 2 different Euler angle set types.Multiple orientations can be input. For N orientations:DCM ===> 3x3xN multidimensional arrayEA### ===> Nx3 matrixEuler Vectors ===> Nx4 matrixQuaternions ===> Nx4 matrixInput includes error check flag that will warn when Euler angles approach singularity or when appropriate values deviate from unity. Fatal errors issued for improper DCM's etc.*****NOTE TO USERS*****I have gotten many questions regarding translation to Euler angle sets. When converting data to Euler angles, you MUST make sure the orientation you are translating is not near a singularity. Singular Euler sets are orientations which cannot be uniquely converted to 3 variables in that particular rotation order. The singular sets are as follows:Type 1 Rotations: 123 - 132 - 213 - 231 - 321 - 312Singular if second rotation angle is -90 or 90 degrees.Type 2 Rotations: 121 - 131 - 212 - 232 - 313 - 323Singular if second rotation angle is 0 or 180 degrees.SpinCalc should now detect when input DCM, EV, or Q correspond to a singular Euler set output. It will prohibit output in such an event.Naturally when converting from these singular Euler angle sets to other data types, you will receive a correct answer. Unfortunately you cannot convert that output back to the correct Euler angle set. This is why singular Euler input is prohibited.Some users may need SpinCalc for the very reason of converting singular Euler sets to the other types. In those cases, removing the prohibiting error check shouldn't be too difficult. Contact me for help if need be.

PLOTXX Create graphs with x axes on both top and bottom Similar to PLOTYY, but ... the independent variable is on the y-axis, and both dependent variables are on the x-axis. For example, you may wish to plot temperature and salinity as a function of depth in the ocean. In the atmosphere, plot temperature and relative humidity as a function of altitude, etc.