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')

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

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.

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).

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

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.

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.

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','')

Ever wish MATLAB had a magnifying glass so you could look at the details of a small region of your plots without having to zoom in and out again and again? Just run 'magnify.m' with the figure of interest as the current figure, then use the left mouse button to bring up a magnified veiw that you control. Or use the 'Ctrl' key while clicking to bring up a magnifying glass that 'locks' onto the figure when released (for use when copying and printing figures). Use the '<' and '>' keys to make the magnifying glass smaller or larger. Use '-' and '+' to decrease or increase the magnification level.

This function creates simple violin plots by estimating the kernel density, using matlabs default ksdensity(). Given a matrix or table with m columns, you will get violins for each of the columns. Key Features:a) Specify plotting features as facecolor, edgecolor, etc. b) Provide data with variable column length as cells if wanted, e.g. Y = [100x1 double] [10x1 double]c) Plot Violins on the desired x-positionNotes:1) This function is not perfect. Please modify it as you like. 2) Please do consider the function by Jonas: "Violin Plots for plotting multiple distributions (distributionPlot.m)" which gets you the histograms as shape. 3) Please note: Kernel density is estimated with ksdensity which uses a gaussian kernel by default. Although the bandwidth is optimal according to the rule of thumb, it is however estimated separately for each violin. For publications, etc., please consider that you might need to use the same kernel bandwidths for all data-subsets in order to be able to really compare the distributions. A beautiful example is given here:http://www.matlabtips.com/beautiful-plots-in-matlab/

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

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)

Shapiro-Wilk parametric hypothesis test of composite normality, for sample size 3<= n <= 5000. Based on Royston R94 algorithm.This test also performs the Shapiro-Francia normality test for platykurtic samples.

This is an embarrassingly simple function to augment the currently available MATLAB colormaps. It works as a seamless replacement for the current maps like jet and hsv. So to use it you just call colormap(othercolor('colorname')). The function handles interpolating to any number of points (othercolor('colorname',numpoints)) and uses the current axis as the reference if numpoints is not specified.The available maps are stored in the file colorData.mat and you can easily add your own maps. To get a list of available names just call othercolor() without any arguments.The 400+ colormaps are from 3 sources:Mathematica (indexed, physical, gradient, and named)http://geography.uoregon.edu/datagraphics/color_scales.htmhttp://www.colorbrewer2.orgSome of these maps are better suited for sets of bar or line plots (particularly the qualitative sets). In those cases the last number in the name is the number of indexed colors, so it would probably be fitting to set M to that number to avoid interpolation. Example:>> figure>> colorscheme = othercolor('Set16',6);>> set(gcf,'DefaultAxesColorOrder',colorscheme);>> plot(rand(6,20));>> legend(num2str((1:6)'))* I'm looking for ideas on how to best organize these maps now that there are 400+ of them. If you have suggestions please leave them in the comments or send me an email.

Many times when contacting MathWorks Technical Support you may be asked to provide recent crash logs generated by MATLAB and sometimes obtaining these logs can be cumbersome. This file automates the extraction of crash logs generated by MATLAB and collects them to a ZIP file you can then send to your Technical Support engineer. Simply execute the function to collect the any logs generated in the past 30 days:>> extractCrashLogsFor more days, execute the function with the number of days as input. For example, for 50 days:>> extractCrashLogs(50)

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)

The function asymp() corresponds to bode(), but it also plots asymptotes for the magnitude and phase graphs. Phase asymptotes are only horizontal and vertical. asymp() only accepts SISO transfer functions.If the transfer function also has a time delay, the time delay is ignoredfor the phase asymptotes.asymp() may be called in two ways only, asymp(h), or asymp(h,wmin,wmax).

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)

FILEFUN is created in the same spirit as e.g. CELLFUN, in that it repeatedly calls the same function FUN with different arguments, in this case filenames. It will then collect the output(s) of the function into concatenated arrays of the same type as FUN delivers, or encapsulated individually in cell arrays.The filename argument to FILEFUN may contain wildcards(*) and FILEFUN may optionally traverse subdirectories recursively.FILEFUN can also be called without the FUN argument, turning it into a recursive wildcard file finder.See 'help filefun' for extensive help and more examples.Examples:Open all figure files in current directory:filefun(@openfig,'*.fig')Pick a couple of image files and compute their mean RGB values:pth=fullfile(matlabroot, 'toolbox', ... 'matlab', 'demos', 'html', filesep);[filenames,pathname]=uigetfile('*.png','Pick files', ... pth,'MultiSelect', 'on');fun=@(fn) squeeze(mean(mean(imread(fn))))';mn=filefun(fun,strcat(pathname,filenames))

NCHOOSE2 - all combinations of two elements Y = NCHOOSE2(X) returns all combinations of two elements of the array X. It is the fast, vectorized version of NCHOOSEK(X,2). X can be any type of array. When X is a scalar integer > 1, it returns X*(X-1)/2. Example:nchoose2([10 20 30 40])% -> 10 20% 10 30% 10 40% 20 30% 20 40% 30 40nchoose2({'a','b','c','d','e'})% -> 'a' 'b' % 'a' 'c' % ...% 'c' 'e'% 'd' 'e' See also nchoosek, perms combn, nchoose, allcomb (on the File Exchange)

This function displays the IEEE double-precision representation of a double in MATLAB. If used with the Symbolic Math Toolbox, it can also display the exact number represented by that IEEE floating point number (which may not be exactly the same as the input; see the Fall 1996 Cleve's Corner article at https://www.mathworks.com/content/dam/mathworks/mathworks-dot-com/company/newsletters/news_notes/pdf/Fall96Cleve.pdf )

This is an extremely fast implementation of the famous Hungarian algorithm (aslo known as Munkres' algorithm). It can solve a 1000 x 1000 problem in about 20 seconds in a Core Duo (T2500 @ 2.00GHz) XP laptop with Matlab 2008a, which is about 2.5 times faster than the mex code "assignmentoptimal" in FEX ID 6543, about 6 times faster than the author's first version in FEX ID 20328, and at least 30 times faster than other Matlab implementations in the FEX.The code can also handle rectangular prolems and problems with forbiden allocations.The new version (V2.3)is able to conduct a partial assignment if a full assignment is not feasible. For more details of the Hungarian algorithm, visit http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html

An updated version of Pplane that works on Matlab R2018b.Copyright to John C Polking, Rice University, 2003 for original version.Updated by Hugh Harvey and George Williams, University of Bristol, 2016.

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.

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 ;-)

Syntax: oldAlpha = setFigTransparency(hFig, alpha, fadeDuration, blockingFlag) Description: setFigTransparency sets the figure hFig's transparency value. The entire figure window, including all internal menus, toolbars and components, is made transparent according to the alpha value. oldAlpha = setFigTransparency(...) returns the old transparency value of the specified figure, prior to its modification. This submission is based on an original idea implemented by Malcolm Lidierth in his MUtilities submission: http://www.mathworks.com/matlabcentral/fileexchange/28326-mutilitiesInput parameters: (all parameters are optional) hFig (default=gcf) - Handle(s) of the modified figure(s). If component handle(s) is/are specified, the containing figure(s) will be inferred and used. alpha (default=0.5) - Transparency value, between 0.0 (=fully transparent) and 1.0 (=fully opaque). Note that all Matlab figure windows are created opaque. alpha<0 indicates that alpha value should not be modified. fadeDuration (default=0) - Number of seconds for fade-in/fade-out effect. Note: default value of 0 means immediately (no fading) blockingFlag - (default=true) Whether or not the function should wait for the fade-in/fade-out effect to complete before returning Examples: oldAlpha = setFigTransparency(hFig,-1); % get hFig's current alpha oldAlpha = setFigTransparency(hFig); % set hFig's alpha to 0.5 (semi-transparent) oldAlpha = setFigTransparency(hFig,0.7); % set hFig's alpha to 0.7 oldAlpha = setFigTransparency([hFig1,hFig2],0.7); % set transparency for several figures oldAlpha = setFigTransparency(hFig,0.3,1.5,false); % non-blocking fade over 1.5 secsBugs and suggestions: Please send to Yair Altman (altmany at gmail dot com) Warning: This code heavily relies on undocumented and unsupported Matlab functionality. It works on Matlab 7.9 (R2009b) and higher, but use at your own risk!

When using MATLAB on windows platforms one could write MEX files to access the WIN32 API functions. However such a tutorial is difficult to find. I decided to post an example with a commented C-MEX file that will demonstrate how to accurately find the windows handle of a MATLAB figure window and then do some API command on it. For simplicity I selected the 'ShowWindow' API because it can be used to solve the 'common' figure maximization problem. (maximizefigure.m sample included)

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

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.

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

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

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'}

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.

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.

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.

Produces a plot who's y-axis skips to avoid unecesary blank spaceReplaces BREAKAXIS

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

This function returns the RGB triplet for almost any color. And unlike the way colors are somewhat officially defined (http://en.wikipedia.org/wiki/Web_colors), this data set describes returns values for the ways that colors are actually perceived on computer monitors. Color names are intuitive because they are based on a survey of over 200,000 user sessions, wherein respondents were shown colors and asked to fill in their word for that color. You won't find "puke green" on Wikipedia's list of web colors, despite the fact that it's a color name that people use and understand. Data come from an XKCD survey described here: http://blog.xkcd.com/2010/05/03/color-survey-results/ A chart of available colors and their most common names can be found here: http://xkcd.com/color/rgb/SyntaxRGB = rgb('Color Name')RGB = rgb('Color Name 1','Color Name 2',...,'Color Name N')RGB = rgb({'Color Name 1','Color Name 2',...,'Color Name N'})DescriptionRGB = rgb('Color Name') returns the RGB triplet for a color described by 'Color Name'.RGB = rgb('Color Name 1','Color Name 2',...,'Color Name N') returns an N by 3 matrix containing RGB triplets for each color name.RGB = rgb({'Color Name 1','Color Name 2',...,'Color Name N'}) accepts list of color names as a character array.

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.

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.

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

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).

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. ----------POLYPARCI Version 2.0 includes options for 1- or 2-tailed t-statistics (default 2), and the probability that a paramerer is different from zero as an additional optional output, in addition to the parameter confidence intervals already provided. It also incorporates the option to use the default value of ‘alpha’ by defining it as [ ], when choosing to define a specific value for the fourth argument, ‘tails’. All outputs are row vectors or a two-row matrix, matching the input parameter vector, required to be a row vector (the default output for ‘polyfit’). As with the earlier version, it is self-contained, requires only MATLAB, and does not requre any additional Toolboxes. It is written with 2023b, however it should be backward-compatible to at least R2012b, since it uses ‘bsxfun’ rather than implicit expansion.

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.

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

This function uses lsqcurvefit to fit parameters D, A, mu, sig to the R^N-->R Gaussian+constant model function, z(x) = D + A*exp( -0.5 * (x-mu).' * inv(sig) *(x-mu) ) Here A and D are unknown scalars, mu is an unknown Nx1 mean vector, and sig is an unknown NxN covariance matrix. By imposing lower and upper bounds 0<=D<=0 (see below), this can also be used to perform pure Gaussian fitting. SYNTAX: [params,resnorm, residual,exitflag,output] = gaussfitn(xdata,zdata,params0,LB,UB,Name,Value) INPUTS (required): xdata: MxN matrix whose rows specify M scattered samples in R^N zdata: Mx1 vector of corresponding samples z(xdata) INPUTS (optional) params0: Cell array of initial parameter estimates {D0,A0,mu0,sig0}. Can also be empty [] in which case default initial guesses are autogenerated. Can also consist of cell array of empty and non-empty elements like {D0,[],mu0,[]} in which case default initial guesses are generated for select parameters. LB: Cell array of lower bounds {D_LB, A_LB, mu_LB} on D, A, and mu. UB: Cell array of upper bounds {D_UB, A_UB, mu_UB} on D, A, and mu. Name,Value: Name/Value option pairs compatible with lsqcurvefit. See, . By default, however, SpecifyConstraintGradient=true unless over-ridden. OUTPUTS: params: Final estimate of the parameters as a cell array {D,A,mu,sig} resnorm: As in lsqcurvefit residual: As in lsqcurvefit exitflag: As in lsqcurvefit output: As in lsqcurvefit

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.

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.

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

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

The "current folder history" stores paths to directories that were once current (it differs from the search path). When paths from networks end up on the current folder history and the network becomes unavailable, an undefined variable or function (often caused by a typo) may cause an unbearable delay in the error message to appear [1,2,3]. To alleviate this problem, this function produces a GUI that lists all paths on the current folder history and you can select which paths to remove from the history. The GUI will create a backup of your original history in case you want to restore it.This was initially developed in Matlab r2017b and does not work with previous releases but the problem did not occur prior to then anyway. Latest release updated in r2021a. To participate in discussions on this topic, mention me (@Adam Danz) in link #2 below. [1] https://www.mathworks.com/matlabcentral/answers/395876-undefined-function-error-is-very-slow-to-occur[2] https://www.mathworks.com/matlabcentral/answers/364153-40-seconds-waiting-for-undefined-function-or-variable-error-2017b[3] https://www.mathworks.com/matlabcentral/answers/412972-matlab-218a-stalls-on-undefined-variables

Existing functions in MATLAB like dec2bin, dec2base, base2dec are limited in scope to work in double precision. So numbers cannot exceed 2^53-1. As well, those tools cannot convert to and from bases higher than 36, due to the character encoding employed. Yes, hex is a nice way to read hexadecimal numbers. But things can get nasty when working in say base 36, because 'O' and '0' can be difficult to distinguish. Finally, the existing tools cannot convert directly between two bases. So if you wanted to move between base 2 and base 3, you might use base2dec, then dec2base. But that forces you to use double precision as an intermediate storage. So if your number exceeded 2^53-1, that scheme would fail.base2base resolves all of those issues, by providing a tool with no limits. If character inputs are provided, it will return a character encoded output, just as the built-in MATLAB tools do. A few examples should show the various problems base2base can solve.Example: Convert decimal numbers 0:10 from base 2 into base 3Nstart = dec2bin(0:10)Nstart =00000001001000110100010101100111100010011010 Nend = base2base(Nstart,2,3)Nend = 000 001 002 010 011 012 020 021 022 100 101 Example: base conversion for a really large number (this conversion was verifed using vpi2base) base2base('1234567890123456789012345678901234567890123456789012345678901234567890',10,8) ans = 26712730460557502321115663104163350570542770265664630627263177431331617605322 Example: hex to binary base2base('FFFBC1234A',16,2) ans = 1111111111111011110000010010001101001010The above examples all worked using character encoded digits. But if we want to go past base 36, that gets more difficult in an encoded form.Example: conversion from base 10 to base 1000 base2base([1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9],10,1000) ans = 123 456 789 123 456 789 Example: conversion between two bases, both of which are larger than 36. I've chosen number bases where the result will be easy to verify here. base2base([233 455 876 342 645],1000,100) ans = 2 33 45 58 76 34 26 45

SHOWWINDOW(NAME,STATE) changes the state of the window with a certain NAME to the specified STATE. STATE must be one of the following:'hide', 'shownormal', 'normal', 'showminimized', 'showmaximized', 'maximize', 'shownoactivate', 'show', 'minimize', 'showminnoactive', 'showna', 'restore', 'showdefault', 'forceminimize', 'max'Examples:>> showwindow('MATLAB','minimize')>> showwindow('','minimize')>> figure(4); showwindow('Figure No. 4','maximize'); text(.5,.5,'Simoneau')

SMOOTHN provides a fast, unsupervised and robust discretized spline smoother for data of arbitrary dimension.SMOOTHN(Y) automatically smoothes the uniformly-sampled array Y. Y can be any N-D multicomponent noisy array (e.g. time series, images, 3D data, 3D vector fields, tensors...). To smooth a vector field or multi-component data, Y must be a cell array. For example, if you need to smooth a 3-D vectorial flow (Vx,Vy,Vz), use Y = {Vx,Vy,Vz}. The output Z is also a cell array which contains the smoothed components.SMOOTHN can deal with missing (NaN) values (see screenshot and examples).SMOOTHN(...,'robust') carries out a robust smoothing that minimizes the influence of outlying data (see screenshot and examples).SMOOTHN is made unsupervised by the minimization of the generalized cross-validation score.Enter "help smoothn" in the Matlab command window for complete instructions and 1-D to 3-D examples.A series of 8 documented examples is available here:http://www.biomecardio.com/matlab/smoothn_doc.html-----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-1178http://www.biomecardio.com/publis/csda10.pdf2) Garcia D. A fast all-in-one method for automated post-processing of PIV data.Exp Fluids, 2011;50:1247-1259.http://www.biomecardio.com/publis/expfluids11.pdf-----

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/02/2023) 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.)

SYNTAX: [success,message] = xlsappend(file,data,sheet)XLSAPPEND Stores numeric array or cell array to the end of specified Excel sheet.REQUIRES ONLY ONE CALL TO THE EXCEL ACTXSERVER, so the overhead is less than for successive xlsread/xlswrite calls.[SUCCESS,MESSAGE]=XLSAPPEND(FILE,ARRAY,SHEET) writes ARRAY to the Excel workbook, FILE, into the area beginning at COLUMN A and FIRST UNUSED ROW, in the worksheet specified in SHEET. FILE and ARRAY must be specified. If either FILE or ARRAY is empty, an error is thrown and XLSAPPEND terminates. The first worksheet of the workbook is the default. If SHEET does not exist, a new sheet is added at the end of the worksheet collection. If SHEET is an index larger than the number of worksheets, new sheets are appended until the number of worksheets in the workbook equals SHEET. The success of the operation is returned in SUCCESS and any accompanying message, in MESSAGE. On error, MESSAGE shall be a struct, containing the error message and message ID.