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))
Helper function for parsing varargin. Makes it easy to write functions that take arguments like this: subaxis(4,2,1,'spacing',0,'marginleft',.1,'H','pt',.1) ArgStruct=parseArgs(varargin,ArgStruct[,FlagtypeParams[,Aliases]]) * ArgStruct is the structure full of named arguments with default values. * Flagtype params is params that don't require a value. (the value will be set to 1 if it is present) * Aliases can be used to map one argument-name to several argstruct fields example usage: -------------- function parseargtest(varargin) %define the acceptable named arguments and assign default values Args=struct('Holdaxis',0, ... 'SpacingVertical',0.05,'SpacingHorizontal',0.05, ... 'PaddingLeft',0,'PaddingRight',0,'PaddingTop',0,'PaddingBottom',0, ... 'MarginLeft',.1,'MarginRight',.1,'MarginTop',.1,'MarginBottom',.1, ... 'rows',[],'cols',[]); %The capital letters define abrreviations. % Eg. parseargtest('spacingvertical',0) is equivalent to parseargtest('sv',0) Args=parseArgs(varargin,Args, ... % fill the arg-struct with values entered by the user {'Holdaxis'}, ... %this argument has no value (flag-type) {'Spacing' {'sh','sv'}; 'Padding' {'pl','pr','pt','pb'}; 'Margin' {'ml','mr','mt','mb'}}); disp(Args)
This MATLAB functions evaluates the Mittag-Leffler (ML) function with two parameters ALPHA and BETA at the square matrix argument AE = ML(A,ALPHA,BETA) evaluates the ML function with two parameters ALPHA and BETA at the square matrix A argument; ALPHA must be any real and positive scalar, BETA any real scalar and A any real or complex square matrix. E = ML(A,ALPHA) evaluates the ML function with one parameter ALPHA at the square matrix A argument; ALPHA must be any real and positive scalar and A any real or complex square matrix.REFERENCES[1] R. Garrappa and M. Popolizio, Computing the matrix Mittag–Leffler function with applications to fractional calculus, Journal of Scientific Computing, 2018, 17(1), 129-153 - doi: https://doi.org/10.1007/s10915-018-0699-5[2] R. Garrappa, Numerical Evaluation of two and three parameter Mittag-Leffler functions, SIAM Journal of Numerical Analysis, 2015, 53(3), 1350-1369.
PIVlab - particle image velocimetry (PIV) tool with GUIPIVlab is a graphical user interface (GUI) based particle image velocimetry (PIV) software. It can be used to control OPTOLUTION's lasers, cameras and synchronizers, and of course it calculates the velocity distribution within imported (or captured) particle image pairs. It can also be used to derive, display and export multiple parameters of the flow pattern. The simple, GUI makes PIV data acquisition and data post-processing fast and efficient.PIVlab comes with it's own unique hardware: Pulsed lasers, LEDs, synchronizers and cameras are available here: Optolution.comVideo tutorial 1/3: Quickstart guidehttps://youtube.com/watch?v=g2hcTRAzBvYVideo tutorial 2/3: Pre-processing, analysis and data validationhttps://youtube.com/watch?v=15RTs_USHFkVideo tutorial 3/3: Data exploration and data exporthttps://youtube.com/watch?v=47NCB_RFiE8PIVlab controlling cameras, lasers, etc.https://youtu.be/8B5M31NWlJcInstallation: https://github.com/Shrediquette/PIVlab/wiki#installation-instructionsPlease ask your questions in the PIVlab forum: http://pivlab.blogspot.de/p/forum.htmlSoftware documentation is available in the wiki: https://github.com/Shrediquette/PIVlab/wikiCode contributors:Main: William Thielicke (http://william.thielicke.org)Name spaces / packages: Mikhil from MATHWORKS (https://github.com/Mikhil11)Vectorization in piv_fftmulti: Sergey Filatov (http://www.issp.ac.ru/lqc/people.html)GUI parallelization: Chun-Sheng Wang, ParaPIV (https://de.mathworks.com/matlabcentral/fileexchange/63358-parapiv)Command line parallelization: Quynh M. Nguyen (https://github.com/quynhneo)Speed, memory and general optimizations: Maarten (https://github.com/mkbosmans) via VORtech.nl via MathWorksWe would like to acknowledge Uri Shavit, Roi Gurka & Alex Liberzon for sharing their code for 3-point Gaussian sub-pixel estimation. Thanks to Nima Bigdely Shamlo for allowing me to include the LIC function. Thanks to Raffel et al. for writing the book "Particle Image Velocimetry, A Practical Guide", which was a very good help. Thanks to the thousands of publications that use PIVlab for research!Visit Matlabs File exchange site for PIVlab: PIVlab can be run online using MATLAB online. MATLAB online is free (after registration) with a limited usage time per user:
A valid IPV4 address is having a format xxx.xxx.xxx.xxx where xxx is having range from 0 to 255. In order to evaluate whether a IP address is Valid or not pass a string to this function containing the IP address you want to Validate . This function returns a value 1 if success else 0 . If any other matlab data types apart from string type are passed to this function then also it returns a value 0. Hope this function will be useful .
This is a utility for setting the value of optional arguments to a function. The first argument is required and should be a cell array of "name, default value" pairs for all optional arguments. The second argument is optional and should be a cell array of "name, custom value"pairs for at least one of the optional arguments. USAGE: argstruct = setargs(defaultargs, varargs)---OUTPUT ARGSTRUCT structure containing the final argument values---INPUTSDEFAULTARGS cell array of "'Name', value" pairs for all variables with default valuesVARARGS [optional] cell array of user-specified "'Name', value" pairs for one or more of the variables with default values. this will typically be the "varargin" cell array. for each pair, SETARGS determines if the specified variable name can be uniquely matched to one of the default variable names specified in DEFAULTARGS. matching uses STRNCMPI and thus is case-insensitive and open to partial name matches (e.g., default variable name 'FontWeight' would be matched by 'fontweight', 'Fontw', etc.). if a match is found, the user-specified value is then used in place of the default value. if no match is found or if multiple matches are found, SETARGS returns an error and displays in the command window information about the argument that caused the problem. ---USAGE EXAMPLE (TO BE USED AT TOP OF FUNCTION WITH VARARGIN)defaultargs = {'arg1', 0, 'arg2', 'words', 'arg3', rand};argstruct = setargs(defaultargs, varargin)
As so many people have asked me the C++ code for calculating besel functions of complex order and complex arguemnt, I now submit them to benifit more people ...
This function randomly partitions data into training, validation and testing data using Cross Validation. Partitioning data in this manner is commonly used for determining the performance of algorithms with free parameters. Training data is commonly used to train the system, the optimum value for the free parameters is determined using validation data. Finally the results of the algorithm are determined using testing data. Matlab has a cross validation but I find it hard to use so I wrote my own. An example determining the optimum kernel with Support vector machines is used. Contact me if you have questions or suggestions
Optional function arguments: optndftsAllows optional arguments to be specified as name value pairs, and default values given for those augments not specified e.g.function strt=demo1(arg1,varargin) % insert values to replace defaultsstrt=optndfts(varargin,'aa',1,'bb',2,'cc',3); % default valuesreturn % optndfts returns a structenddemo1(123,'bb',22,'aa',11)ans = aa: 11 bb: 22 cc: 3Result is a struct, varagin input values can be list of name value pairs, cell array of name value pairs, or a struct.Also can allow for optional arguments that are not named:function strt=demo2(arg1,varargin) % insert values to replace defaultsstrt=optndfts(varargin,{'aa','bb'},'aa',1,'bb',2,'cc',3,'dd',4);return % optndfts returns a structenddemo2(123,11,22,'dd',44)ans = aa: 11 bb: 22 cc: 3 dd: 44demo2(123,11,'dd',44)ans = aa: 11 bb: 2 cc: 3 dd: 44demo2(123,'dd',44)ans = aa: 1 bb: 2 cc: 3 dd: 44A second output argument if present is a struct containing name value pairs not given in the default values, these can be used to override defaults for functions called within original function.Functions selectfields and renamefields, with error messages suppressed, can also be used to assist in passing options from an outer function to nested functions (see doc selectfield, and doc renamefields).Test files contain examples.See doc optndfts
Assigns named arguments passed to your function to local variables (as in plot(), etc.). The name of the argument is the name of the local variable in your function. Example: inputfun('prompt', '>', 'defval', 5.1, 'timeout', 5);This is the same idea as Matlab's inputParser, but with a focus on being really simple and easy to use. Other implementations of this idea on File Exchange require a lot of lines of code to set this up, where as my code just requires one extra function call near the top of your function. Usage: (1) in your function, define local variables with their default values; (2) call procArgs(varargin) Minimal error checking: requires that all passed variable names match already defined variables in your function. It would be pretty easy to add type checking if you wanted it (I don't, particularly). Example: function test(varargin) name = 'John'; age = 32; procArgs(varargin) fprintf('name=%s, age=%i\n', name, age); %% example calls test('name', 'Amber'); % prints Amber, 32 test('age', 99); % prints John, 99 test('Ages', 0); % error, will report that Ages is not defined.
Jx-DLT : Deep Learning Toolbox* This toolbox contains the convolution neural network (CNN) * The < Main.m file > shows examples of how to use CNN programs with the benchmark data set. Note we demo the CNN using one to three convolution layers setup.* Detail of this toolbox can be found at https://github.com/JingweiToo/Deep-Learning-Toolbox**********************************************************************************************************************************
This function is analogous to the builtin lambertw() except that it accepts the logarithm of the argument:lambertw(0,exp(logx)) == lambertwlog(logx) (within machine precision)This function only supports real values of logx and the principal branch of the Lambert W function (lambertw(0,x) for real, nonnegative x). For complex arguments or to evaluate alternative branches, use the builtin lambertw() function.The logarithmic input allows for much larger arguments than the builtin lambertw(). For example, lambertw(exp(710)) == Inf % exp(710) == Inflambertwlog(710) == 703.44lambertwlog(10000) == 9990.79Though limited in domain, this function is hundreds of times faster than the builtin version (as of MATLAB 8.5).
validateInput started when creating saveppt2. There was a need to take a large number of inputs, in any order, and make them usable to the script. Checking if an input argument has been passed can be done with isfield or if the 'force' option is enabled if the field is false.Examples:varargin={'p','s',10,'name','john doe'}; validParameters={{'size','s'},{'print','p'},'name'}; parameters=validateInput(varargin,validParameters)parameters = print: 1 size: 10 name: 'john doe'varargin={'p'} validParameters={{'size','s'},{'print','p'},'name'} parameters=validateInput(varargin,validParameters,true)parameters = print: 1 size: 0 name: 0
FDEP dissects MATLAB files and iteratively looks for all user defined functions (modules), which are used during runtimeFDEP retrieves for each module its- subfunctions- nested functions- anonymous functions- eval class calls- unresolved calls and all- ML stock functions- ML built-in functions- ML classes- ML toolboxes that it usesruntime options and returned macros create user-friendly,intuitively comprehensible, and interactive GUIs, which- list the results in various panels and listboxes- plot a full synopsis for each module with exhaustive information- plot a full dependency matrix- plot a runtime and modules treein essence, FDEP is a wrapper for DEPFUN and MLINT; however, due to an efficient pruning engine it is considerably (20-100 times!) fasterFDEP is particularly useful if you want to distribute your functions and need so see what else to include as well as the toolboxes they useFDEP may be useful to debug an erroneous function with correct syntaxsee> help fdepand the accompanying published M-file for help and an exhaustive example
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)
Procrustes cross-validation is a new approach for validation of chemometric models. It makes possible to generate a new dataset, named "PV-set" and use it for validation of models in the same way as with an independent validation set. The current implementation supports Principal Component Analysis (method "pcvpca()", Principal Component Regression (method "pcvpcr()") and Partial Least Squares (method "pcvpls()") models.Check Getting started documentation and see more details here: https://github.com/svkucheryavski/pcv.
Predictive Estimation of Model Fidelity (PEMF) is a model-independent approach to measure the fidelity of surrogate models or metamodels, such as Kriging, Radial Basis Functions (RBF), Support Vector Regression (SVR), and Neural Networks. It can be perceived as a novel sequential and predictive implementation of K-fold cross-validation. PEMF takes as input a model trainer (e.g., RBF-multiquadric or Kriging-Linear), sample data on which to train the model, and hyper-parameter values (e.g., shape factor in RBF) to apply to the model. As output, it provides a predicted estimate of the median and/or the maximum error in the surrogate model. PEMF has been reported to be more accurate and robust than typical leave-one-out cross-validation, in providing surrogate model error measures (for various benchmark functions). The current version of PEMF has been implemented with RBF (included in this package), Kriging (DACE package), and SVR (Libsvm package), PEMF (has been and) can be readily used for the following purposes:1. Surrogate model validation2. Surrogate model uncertainty analysis3. Surrogate model selection4. Surrogate-based optimization (to guide sequential sampling)Other perceived broader applications of PEMF include testing of machine learning models and uncertainty analysis with data-driven models (and other areas where leave-one-out or k-fold cross-validation is typically used). Cite PEMF as:A. Mehmani, S. Chowdhury, and A. Messac, "Predictive quantification of surrogate model fidelity based on modal variations with sample density," Structural and Multidisciplinary Optimization, vol. 52, pp. 353-373, 2015.This is the first release of PEMF; so, any feedback or information on any bugs (that we might have missed) is very welcome.
Based on same idea as the excellent "parse_pv_pairs", and similar to the "inputParser" object added to MATLAB in R2007a, this function handles names and values for properties in any order, and assigns the values to a structure containing default values.For example, in your function which has options "StartTime" and"StopOnError", create a structure of defaults and pass inputs to parseargs:| function myfunction(varargin)| X.StartTime = 0;| X.StopOnError = true;| X = parseargs(X,varargin{:})If the user specifies inputs:| myfunction('StopOnError',false,'StartTime',5)the structure will be modified accordingly.The aim of this function is to ease as much as possible the tedious and error prone task of handling inputs, specifically with a view to application development (rather than quick scripting), where robustness is of high importance. To this end, the function enforces some rules, partly to reduce the chance of mistakes by the caller, and partly to save the user from writing additional code to enforce them:1) Property names must be specified in full, and are case-sensitive2) The data type of a property cannot be changed (unless the property was initially empty)3) Scalar values must remain scalar4) Where the original value is a cell array it must contain strings. The new value must be one of these strings, and if no new value is specified, the first string is selected as a default.
The function takes two images as argument and using edge detection checks whether they are the same or not...a cool and simple code which can be used in security systems. The level at which the two pictures should be matched can be controlled.
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)
Useful for assigning defaults to functions that use varargin or structs of input parameters (alternative to inputParser).See examples (and latest updates) on the github repository:https://github.com/nvictus/ArgUtils- Use ArgUtils.assignVars() to assign variables sequentially- Use ArgUtils.assignArgs() to assign named variables: it works on either struct input or cell-array input containing a sequence of values followed by keyword arguments (name-value pairs) in any order. Keywords are matched using MATLAB's string validator, so matching is case-insensitive and abbreviated keywords are acceptable as long as they can be matched unambiguously. There are also options to specify:- required input parameters- prefixes on keywords to prevent name collisions with string values
Here are two functions: xyzread reads text .xyz files into your Matlab workspace. This is written for GMT-generated .xyz files, but may work for other .xyz files as well. xyz2grid converts the columnated data from a .xyz file into a gridded dataset that can be viewed with surf, pcolor, or imagesc. Note: this function does not interpolate! It simply reshapes the z values from a column of z data and puts them into a 2D matrix.
Cluster validation is an important and necessary step in cluster analysis. This visual cluster validation tool CVAP based on GUI provides important tools and convenient analysis environment for validity evaluation of clustering solutions, estimation of the number of clusters and performance comparison between candidate clustering algorithms. CVAP includes 4 External validity indices, 14 Internal validity indices and 5 clustering algorithms (K-means, PAM, hierarchical clustering and etc.). It supports other clustering algorithms via loading a solution file with class labels, or by adding new codes. And similarity metrics of Euclidean distance and Pearson correlation coefficient are supported. Some useful information and references are in help files "Readme.txt", please read them first.
nargchk is used almost exclusively in one way:error(nargchk(minargs, maxargs, nargin, 'struct'));The third and fourth arguments are always the same, and you always wrap it in an error call.This stupidly simple function saves you typing, and prettifies your code by wrapping the above line into something more readable, namelyCheckNumberArgs(minargs, maxargs);
You need to add LibSVM into MATLAB path before using this.
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 ;-)
This function creates two cell arrays, one with training data and the other with testing data. The testing sample size is determined by the number of samples divided by the desired K values. If the terms are not divisible, the function will truncate the least number of points to perfectly divide the sample size by K. You have the option to choose if the testing and training sets samples are chosen at random by turning shuffle 'on' or 'off'.The input data must be in column vectors/matrices, if the function believes you have entered a row vector/matrices it will automatically transpose the data. Check the functions help section for more details.Cites:https://en.wikipedia.org/wiki/Cross-validation_(statistics)
A numerical evaluator for the generalized hypergeometric function for complex arguments with large magnitudes using a direct summation of the Gauss series.pFq isdefined by (borrowed from Maple): pFq = sum(z^k / k! * product(pochhammer(n[i], k), i=1..p) / product(pochhammer(d[j], k), j=1..q), k=0..infinity )The desired accuracy (number of digits) can be specified as a parameter.This function is a translation from the original fortran77 source code written by W. F. Perger from the Michigan Technological University.
This submission demonstrates Power Plant Model Validation as applied to online performance monitoring of grid events using phasor measurement unit (PMU) data, through a workflow that includes both manual adjustments and automated techniques. Both gas plant and steam plant examples are included. Data is from the NASPI Technical Workshop - Model Verification Tools. The data is stylized and does not represent actual equipment. More details on the workshop can be found at the following link - https://www.naspi.org/node/528For more information on MathWorks solutions for Power Systems Analysis and Design, please visit this page https://www.mathworks.com/solutions/power-system-analysis-and-design.htmlYou can use this submission in MATLAB Online. From the Home Tab, select Add-Ons -> Get Add-Ons and search for the submission name in the Add-On Explorer. Navigate to the submission page, click the Add button and select Save to MATLAB Drive.
[Kxy,Lxy]=cedawSeu(x,y).This program file computes the complex error function with small imaginary argument 0≤y≤ 0.1. In the real and imaginary parts this program provides average accuracy exceeding 1e-15 and 1e-16, respectively.The code is written by Yihong Wang(email:wyh@seu.edu.cn), Southeast University, China, April 2020. Feel free to email the author of this program with your questions or suggestions.
Extends the argument validation functions:https://www.mathworks.com/help/matlab/matlab_prog/argument-validation-functions.htmlmustBePowerOf2(numbers) validates if all the numbers of an array are a power of 2, i.e., check if for every number n in the array log2(n) = k, where k is a non-negative integer. The function throws an error if any number of the array is not a power of 2.Note: If you want to also check for powers of 2 when k is a negative integer, i.e., fractions where the denominator is a power of 2, you can simply remove the "numbers(iter) < 1 " from the if clause.
This function is a generalization of BSXFUN, provided as a builtin function in MATLAB R2007a and later releases. It is part of the ARRAYLAB toolbox, together with MULTIPROD (MATLAB Central, file #8773) and the Vector algebra toolbox (MATLAB Central file #8782).BAXFUN is called by some of the functions in the vector algebra toolbox.C = BAXFUN(FUNC, A, B) applies an element-by-element binary operation to arrays A and B, with singleton expansion (SX) enabled. It is equivalent to C = BSXFUN(FUNC, A, B). FUNC is a function handle.C = BAXFUN(FUNC, A, B, SHIFTA, SHIFTB) applies an element-by-element binary operation to arrays A and B, with array expansion (AX) enabled. FUNC is a function handle. SHIFTA and SHIFTB specify the number of dimensions by which arrays A and B are optionally shifted to the right (positive values) or left (negative values). Thus, C = BAXFUN(FUNC, A, B, SHIFTA, SHIFTB) is equivalent to C = BAXFUN(FUNC, SHIFTDIM(A,-SHIFTA), SHIFTDIM(B,-SHIFTB)).C = BAXFUN(FUNC, A, B, SHIFTA) can be used if B is not to be shifted. FUNC can either be an handle for an M-function, or one of the following built-in-function handles: @plus Plus @minus Minus @times Array multiply@rdivide Right array divide@ldivide Left array divide@power Array power @max Binary maximum @min Binary minimum @rem Division remainder @mod Division modulus@atan2 4-quadrant arc-tangent@hypot SQRT of sum of squares@eq Equal@ne Not equal@lt Less than@le Less than or equal@gt Greater than@ge Greater than or equal@and Logical AND@or Logical OR@xor Logical EXCLUSIVE ORIf an M-function handle is specified, the M-function must be able to accept as input either two column vectors of the same size, or one column vector and one scalar, and return as output a column vector of the same size as the input(s). Array expansion (AX) is a powerful generalization of the concept of scalar expansion. Scalar expansion is the virtual replication or annihilation of a scalar which allows you to combine it, element by element, with an array X of any size (e.g. X+10, X*10, or []-10). Similarly, in BAXFUN, the purpose of AX is to virtually match the sizes of A and B, before FUNC is applied. Indeed, A and B can be scalars, vectors, matrices, or multi-dimensional arrays, and may have different sizes. Dimension matching is achieved by means of a dimension shift followed by a singleton expansion: 1) DIMENSION SHIFTA dimension shift (see SHIFTIM) is applied to A or B if a non-zero value is specified for SHIFTA or SHIFTB. Notice that, in BAXFUN, a shift to the left is hardly ever needed. Hence, positive values of SHIFTA/B indicate a shift to the rigth, and negative values a shift to the left, whereas SHIFTDIM uses the opposite convention. 2) SINGLETON EXPANSION (SX)Whenever a dimension of either A or B is singleton and the corresponding dimension of the other array is not, the mismatch is fixed by virtually replicating (or diminishing to length 0) the array along that dimension. BAXFUN applies elementwise operations. Matrix multiplications with AX enabled can be performed using MULTIPROD (MATLAB Central, file #8773). BAXFUN calls the builtin function BBXFUN, available in MATLAB R2007a. For earlier MATLAB releases, use Schwarz's replacement of BSXFUN (MATLAB Central, file #23005) Examples:Subtracting the column means from a matrix A a = magic(5); % ................. 5×5 a = baxfun(@minus, a, mean(a)); % 5×5 Subtracting the matrix means from 10 matrices contained in A a = rand(3, 3, 10); % ............... 3×3×10 means = mean(reshape(a, 9, 10)); % .... 1×10 a = baxfun(@minus, a, means, 0, 1); % 3×3×10 Multiplying matrix A by each element of B, i.e. multiplying eachelement of A by each element of B (all possible combinations) a = [1 2 3 4; 5 6 7 8]; % ....... 2×4 b = [1 10 100]; % ................. 1×3 c = baxfun(@times, a, b, 0, 1); % 2×4×3 c(:,:,1) = 1 2 3 4 5 6 7 8 c(:,:,2) = 10 20 30 40 50 60 70 80 c(:,:,3) = 100 200 300 400 500 600 700 800
The Matrix Function Toolbox is a MATLAB toolbox connected with functions of matrices. It is associated with the book Functions of Matrices: Theory and Computation and contains implementations of many of the algorithms described in the book. The book is the main documentation for the toolbox.The toolbox is intended to facilitate understanding of the algorithms through MATLAB experiments, to be useful for research in the subject, and to provide a basis for the development of more sophisticated implementations. The codes are "plain vanilla" versions; they contain the core algorithmic aspects with a minimum of inessential code. In particular, the following features should be noted. * The codes have little error checking of input arguments. * The codes do not print intermediate results or the progress of an iteration. * For the iterative algorithms a convergence tolerance is hard-coded (in function mft_tolerance). For greater flexibility this tolerance could be made an input argument. * The codes are designed for simplicity and readability rather than maximum efficiency. * Algorithmic options such as preprocessing are omitted. * The codes are intended for double precision matrices. Those algorithms in which the parameters can be adapted to the precision have not been written to take advantage of single precision inputs.
ispathvalid & mustBeValidPath: Validate path syntax, type, and extensionThe typical use case is to check paths at the start of a script/function before saving/exporting, with human readable feedback if validation fails.Syntaxtf = isvalidpath( inputPath ) checks if the platform can parse the path inputPath. Unlike isfolder and isfile, it does not verify that the path exists in the file system.tf = isvalidpath( inputPath, pathType ) also checks that the location of inputPath is either a file or directory.tf = isvalidpath( inputPath, "file", validExtensions ) also checks that inputPath contains a file extension from a provided set, validExtensions.[ tf, Log ] = isvalidpath( __ ) additionally returns formatted log messages. Log.warning explains why a path is not valid. Log.info provides formatting tips. Use the disp function to print the log to the command window.mustBeValidPath( inputPath, pathType, validExtensions ) function identically to isvalidpath but throws an error if the path format is not valid. pathType and validExtensions are optional.InputsArgumentDescriptioninputPathPath to validate.Supported path formats:Traditional path, to a file or directory, relative or absolute, e.g., C:\ffmpeg and ../file.dat.Unsupported path formats:Remote locations, e.g., s3://bucketname/.UNC paths, e.g., \\127.0.0.1\temp.DOS device paths, e.g., \\.\UNC\Server\Share\.URIs, e.g., file://C:/file.dat and http://example.com.All others not listed here.Text scalar, i.e., character vector or string scalar.pathTypeValid location type of inputPath. Either:"any" - (default) Any path type is acceptable."file" - Only a file path is acceptable, i.e., it must have a file name and a valid extension according to validExtensions."dir" - Only a directory path is acceptable, i.e., it cannot have a file name or extension."directory" - Same as "dir". Text scalar, i.e., character vector or string scalar.validExtensionsSpecifies which file extensions are valid if the input is a file path. Each entry must be either:(default) A period (.), representing any extension.Text beginning with a period character, e.g., ".mat".Empty text, {''} or "", representing no extension."image", representing all raster image extensions MATLAB knows. Run the command [ imformats().ext ] to see the list.Character vector, cell array of character vectors, or string array.OutputsArgumentDescriptiontfWhether the path valid or not according to the above options.Logical scalar.LogFormatted log messages. Struct scalar with the fields:warning - String. Explains why the path is not valid, or states when the location is ambiguous, e.g., "C:\example" could be either a directory or a file without an extension. Possible warning messages:Invalid path as per platform rules, e.g., "dir\dir\dir\:".Directory path includes a file extension, e.g., "dir\file.ext".File path lacks a file name, e.g., "dir\".File path missing valid user-specified extension, e.g., "dir\file".Path could be a file OR a directory, e.g., "dir\ambiguous". The path may still be valid.info - String. Contains additional formatting information and explains formatting issues which will not affect the use of path in practice, as they are handled correctly by the platform. Possible info messages:Path altered by platform during parsing, e.g., any of the below.Redundant name elements removed by platform, e.g., ".\dir".Path has incorrect separators for platform, e.g., "dir\dir/dir".Path includes consecutive separators, e.g., "dir//dir/".If there are no messages, the fields of Log will be "", i.e., a zero length string. Use the disp function to print the messages to the command window, e.g., disp( Log.warning ).Exampleload( "spine.mat", "X" )X = X / max( X, [], "all" );outputFile = "output\xray.jpg";validExts = ["" ".mat" "image"];[ isSave, Log ] = isvalidpath( outputFile, "file", validExts );if isSave [ filePath, ~, fileExt ] = fileparts( outputFile ); if ~isfolder( filePath ) [ status, msg ] = mkdir( filePath ); assert( status == 1, ... "Could not make output directory:\n -\t%s", msg ) end try if strcmp( fileExt, "" ) || strcmp( fileExt, ".mat" ) save( outputFile, "X" ) else imwrite( X, outputFile ) end fprintf( "Saved patient scan to '%s'.\n", outputFile ) catch ME warning( ME.identifier, ... "Patient scan not saved:\n -\t%s", ME.message ) endelse warning( "Patient scan not saved. " + ... "outputFile is not a valid.\n\n%s\n", Log.warning )endNotesCreated in 2022b. Compatible with MATLAB release 2019b and later. Compatible with all platforms.Published under MIT License (see LICENSE.txt).Please cite George Abrahams (GitHub, LinkedIn, Google Scholar).
Transfer Function Analysis of Dynamic Systems or Curriculum ModuleCreated with R2020b. Compatible with R2020b and later releases.InformationThis curriculum module contains interactive MATLAB® live scripts and apps that teach transfer function analysis of dynamic systems.BackgroundYou can use these live scripts as demonstrations in lectures, class activities, or interactive assignments outside class. In the first script, students learn to derive transfer functions from ODEs and compute impulse, step, and forced responses. In subsequent scripts, students perform pole-zero and frequency domain analyses. Throughout the module, students apply transfer functions to analyze the dynamics of physical and electrical systems. In the final lesson, students perform a frequency domain analysis of an LC filter in a buck converter. A review of Laplace transforms is also included for students seeking a refresher. In addition, there is a MATLAB app that lets you construct a transfer function by graphically positioning the poles and zeros. You can also compute and plot the impulse and step responses.The instructions inside the live scripts will guide you through the exercises and activities. Get started with each live script by running it one section at a time. To stop running the script or a section midway (for example, when an animation is in progress), use the Stop button in the RUN section of the Live Editor tab in the MATLAB Toolstrip.Contact UsSolutions are available upon instructor request. Contact the MathWorks teaching resources team if you would like to request solutions, provide feedback, or if you have a question.PrerequisitesThis module assumes knowledge of algebra and differential equations. There is minimal MATLAB knowledge required for these scripts and app, but you could use MATLAB Onramp and Introduction to Symbolic Math with MATLAB as a resource to acquire familiarity with MATLAB syntax, live scripts, and apps.Getting StartedAccessing the ModuleOn MATLAB Online:Use the link to download the module. You will be prompted to log in or create a MathWorks account. The project will be loaded, and you will see an app with several navigation options to get you started.On Desktop:Download or clone this repository. Open MATLAB, navigate to the folder containing these scripts and double-click on TransferFunctions.prj. It will add the appropriate files to your MATLAB path and open an app that asks you where you would like to start.Ensure you have all the required products (listed below) installed. If you need to include a product, add it using the Add-On Explorer. To install an add-on, go to the Home tab and select Add-Ons > Get Add-Ons.ProductsMATLAB is used throughout. Tools from Symbolic Math Toolbox™ and Control System Toolbox™ are used frequently as well.ScriptsIf you are viewing this in a version of MATLAB prior to R2023b, you can view the learning outcomes for each script hereConceptReview.mlxIn this script, students will...Academic disciplines• Compute Laplace transforms by hand and using symbolic math • Describe the properties of the Laplace transform • Apply Laplace transforms to solve initial value problems • Recall the definition of a linear time-invariant (LTI) operator• Mechanical Engineering • Electrical Engineering • MathematicsTransferFunctionBasics.mlxIn this script, students will...Academic disciplines• Derive transfer functions by hand • Derive transfer functions using symbolic math • Numerically evaluate and plot the impulse, step, and forced responses of a system • Analytically derive the step and forced responses of a system • Explain the physical significance of time responses• Mechanical Engineering • Electrical Engineering • MathematicsPoleZeroAnalysis.mlxIn this script, students will...Academic disciplines• Describe how the transfer function of a DC motor is derived • Identify the poles and zeros of a transfer function • Assess the stability of an LTI system based on the transfer function poles • Relate the position of poles in the s-plane to the damping and natural frequency of a system • Explain how poles of a second-order system relate to its dynamics • Examine how transfer function zeros affect the dynamics of a system• Mechanical Engineering • Electrical Engineering • MathematicsFrequencyDomainAnalysis.mlxIn this script, students will...Academic disciplines• Explain how a Bode plot is generated • Use MATLAB to numerically calculate the frequency response of a transfer function • Discuss how features of the Bode plot relate to characteristics of physical systems • Describe how to derive a differential equation model for a buck converter with an LC filter • Apply the Bode plot to analyze an LC filter in a buck converter • Mechanical Engineering • Electrical Engineering • MathematicsLicenseThe license for this module is available in the LICENSE.md.Related Courseware ModulesFourier AnalysisAvailable on: GitHubVirtual Hardware and Labs for ControlsAvailable on: GitHubFeel free to explore our other modular courseware content.Educator ResourcesEducator PageContributeLooking for more? Find an issue? Have a suggestion? Please contact the MathWorks teaching resources team. If you want to contribute directly to this project, you can find information about how to do so in the CONTRIBUTING.md page on GitHub.© Copyright 2023 The MathWorks™, Inc
As is well known, if f() is linear function then there exists a matrix A such that for any Y=f(X), where X and Y are array-valued input/output arguments, the operation can equivalently be expressed Y(:)=A*X(:). In MATLAB, we are often given linear operations f() in function form only, but need the matrix form to do linear algebraic manipulations: transpose, pseudo-inversion, etc... The file FUNC2MAT in this submission computes the matrix A given a handle, fun, to any linear mapping from N-dimensional to M-dimensional space. An alternative and faster version LOCALFUNC2MAT is also available for certain types of linear transformations where impulse inputs have very localized responses in the output. Many image transformation functions like INTERPN, IMWARP, IMROTATE, etc... satisfy this property.See the Examples tab for demonstrations of use.
MathWorks ®️ Tool Validation Kit ApplicationTable of ContentsTool Validation Kit ApplicationBackgroundCode OverviewGetting StartedBackgroundThe goal of this work is to provide an example tool validation suite to for commercial off-the-shelf software tools from MathWorks. To comply with the US Food and Drug Administration’s Quality System Regulations, any software tool that is used as part of a medical device development process must be validated as fit for its intended use. Such validation requires documentation of context of use, risks of failure, and mitigation strategies. As this effort is use-case specific, it is outside the scope of this project. However, a very common risk mitigation strategy for commercial off-the-shelf software is to run a set of validation tests to confirm correct results on the end user’s computer system. This project helps automate the construction and execution of such a suite of tool validation unit tests. The resulting test report may be used as evidence for completion of a software validation plan. Some key aspects of the package includeA MATLAB ®️ app to run a collection of unit tests and report on their outcomeA collection of unit tests for base MATLAB features and features of some MATLAB toolboxes and add-onsA template for adding new tests to cover additional use casesDocumentation such as MathWorks product quality statements and user guidesAn optional installer to add the TVK to a MATLAB installation as an add-on toolboxThis version works with MATLAB R2023bCode OverviewThe project code is organized into eight folders: app, demos, documentation, documents, release, source, test, and UnitTestFolder.The app folder contains the files needed to run the TVK Application UI. The files contain both programmatic execution of the app, as well as the App Designer file (TVKApp.mlapp).The demos folder contains one demo:Getting Started - Tool Validation Kit CLI Demodemo_TVK.mlxThe documentation folder contains all files required for generating the custom documentation in the Supplemental Software section of the MATLAB:registered: documentation. Please navigate to the "Supplemental Software" section of the MATLAB doc after toolbox installation to access the documentation.The documents folder contains further documentation on getting starting with the Tool Validation Kit, including:MATLAB Tool Validation Suite User GuideTool Validation Kit App GuideMATLAB-Quality-StatementSimulink ®️ -Quality-StatementThe release folder contains the toolbox packaging files for installing the source code and TVK UI.The source folder contains all the code for implementing the TVK tool, which is organized in the +tvk package. Type tvk. on the command line followed by the Tab key to list available classes and methods. You can also type help tvk to list all contents in the +tvk package.There are two main component of the tvk package:@TVKBase: This class implements an interface for running the tool validation kit, including running tests and generating reports. Type help tvk.TVKBase into the command window for the full list of properties and methods.utilities: Convenience functions used in both the source and app code.The test folder contains all software unit/integration tests and corresponding utilities. In order to execute all tests, select the runAllTests button in the Projects Shortcuts tab, or execute this function in the command window. This folder contains the following components:app: App-based unit tests for TVKApp.mlapp.unit: Unit tests focused on the @TVKBase class methods.utilities: Convenience functions used in the test classes to find project data root location, generate expected results, and run all tests with support for GitLab CI.To learn more about testing software and continuous integration in MATLAB, refer to the following documentation links:MATLAB Unit Test FrameworkContinuous IntegrationThe UnitTestFolder contains pre-written collection of test cases for various toolboxes including:MATLABComputer Vision Toolbox ™️Deep Learning Toolbox ™️Image Processing Toolbox ™️Signal Processing Toolbox ™️Statistics and Machine Learning Toolbox ™️Getting StartedTo get started using the TVK tool, please follow the steps below:Open the MATLAB Project by selecting the TVKApp.prj file.Open the TVKApp.mlapp and the user guide to run the tool interactively and/orFollow the steps in demo_TVK.mlx live script for instructions on how to use the tool for selecting test cases, running the test suite, and generating the report.Alternatively, if you would like to avoid opening the MATLAB project each time, you can install the "Tool Validation Kit.mltbx" toolbox file found in the release folder, which will install all custom documentation and allow you to use the app and CLI without modifying any source code.
In this project, a MANET simulated. For each packet delivery, a number of routes will be provided and the best and the safest route will be selected using an MLP neural network. This will cause a higher PDR (packet delivery rate).
Struve functions are usually encountered when computing Bessel function integrals.In this submission, the first two orders of the Struve function H0(z) and H1(z) are computed for vector/matrix complex arguments. Additionally, routines are provided for the corresponding functions H0(z)-Y0(z) and H1(z)-Y1(z), useful for large z, and for the modified functions L0(z) and L1(z).These are high precision routines. They were tested against mfun and the hypergeometric function of Matlab and agreement is 14 significant digits. Regarding computation time they are orders of magnitude faster for large matrix arguments. When comparing to Mathematica results, please note that in some arguments regions, different Mathematica versions give different results.The method used was Chebyshev expansions for abs(z)<=16 and rational approximations for abs(z)>16 with mapping on the right half complex plane for the latter case. Matlab routines bessely and besselh are used. A relevant Chebyshev routine is also included.I would be grateful to receive any comments for further expanding the routines.
C++ source code for compiled plugins (MEX files) to compute various error functions for complex arguments:** Faddeeva_erf(z) -- the error function** Faddeeva_erfc(z) = 1 - erf(z) -- complementary error function** Faddeeva_erfi(z) = -i erf(iz) -- imaginary error function** Faddeeva_erfcx(z) = exp(z^2) erfc(z) -- scaled complementary error function** Faddeeva_w(z) = exp(-z^2) erfc(-iz) -- Faddeeva function** Faddeeva_Dawson(z) = 0.5 sqrt(pi) exp(-z^2) erfi(z) -- Dawson functionFrom e.g. the Faddeeva function, one can also obtain the Voigt functions and other related functions.Assuming you have a C++ compiler (and have configured it in MATLAB with mex -setup), compile by running the included Faddeeva_build.m script in MATLAB: Faddeeva_buildAll of the functions have usage of the form: w = Faddeeva_w(z)or optionally Faddeeva_w(z, relerr), where relerr is a desired relative error (default: machine precision). z may be an array or matrix of complex or real numbers.This code may also be downloaded from http://ab-initio.mit.edu/Faddeevaalong with documentation and other versions. As described in the source code, this implementation uses a combination of algorithms for the Faddeeva function: a continued-fraction expansion for large |z| [similar to G. P. M. Poppe and C. M. J. Wijers, "More efficient computation of the complex error function," ACM Trans. Math. Soft. 16 (1), pp. 38–46 (1990)], and a completely different algorithm for smaller |z| [Mofreh R. Zaghloul and Ahmed N. Ali, "Algorithm 916: Computing the Faddeyeva and Voigt Functions," ACM Trans. Math. Soft. 38 (2), 15 (2011).]. Given the Faddeeva function, we can then compute the other error functions, although we must switch to Taylor expansions and use other tricks in certain regions of the complex plane to avoid cancellation errors or other floating-point problems.
Validoozy for Matlab====================In R2017a, Matlab introduced "mustBe*()" validator functions, for doing declarative-ish constraints on properties and function arguments. Validoozy provides additional validator functions in this style.The Mcode/extend directory provides new validator functions that Matlab doesn't provide, but I've found useful in my coding.The Mcode/compat directory provides re-implementations of the Matlab R2017a validator functions for use in older versions of Matlab.To use Validoozy, copy it to somewhere on your hard drive, and run the `Mcode/load_validoozy` function in Matlab. That will add the required directories to your Matlab path.The Validoozy project lives at https://github.com/apjanke/matlab-validoozy. Bug reports and feature requests are welcome.Functions---------Validoozy provides the following functions:extend (new functions): makeItBeA(x, type) mustBeA(x, type) mustBeCellstr(x) mustBeCharvec(x) mustBeSameSize(a, b) mustBeScalar(x) mustBeScalarLogical(x) mustBeVector(x) size2str(sz)compat: mustBeFinite(x) mustBeInteger(x) mustBeMember(x, valid) mustBeNonempty(x) mustBeNumeric(x) mustBeReal(x)
The digamma or Psi (Maple) or Polygamma (Mathematica) function for complex arguments.FDIGAMMA(Z) returns the digamma function of the complex scalar/matrix Z.
TYPECAST and TYPECASTX are mex functions intended to mimic the MATLAB intrinsic typecast function with extensions. These C-mex versions of typecast differs from the intrinsic typecast in the following important aspects: Intrinsic typecast------------------Type of copy: Deep Data CopyAllows complex: NoAllows logical: NoAllows char: NoAllows non-vector: NoC-mex typecast--------------Type of copy: Shared Data CopyAllows complex: YesAllows logical: Yes (cannot convert from complex)Allows char: Yes (cannot convert from complex)Allows non-vector: YesSince these C-mex functions produce a shared data copy of the original, it is more efficient than the MATLAB intrinsic typecast, which may be important if you are working with large variables. For non-vector inputs, the first non-singleton dimension must be compatible for the conversion.There is *NO* difference in functionality between the C-mex typecast and typecastx functions. The purpose of including typecastx is so that users can have the extended functionality shown above without shadowing the intrinsic typecast. e.g., users with older versions of MATLAB that do not have a MATLAB intrinsic typecast might install both typecast and typecastx, whereas users with later versions of MATLAB that *do* have an intrinsic typecast might choose to only install the typecastx function.Note that these C-mex functions are self-building ... you don't have to know anything about C.
I used to use Maple to check my equations, The ability of seeing the equation in the pretty print mode in maple has helped me to validate my code and recognize the errors in my equations for years, Even when I was using MATLAB I used to have Maple open to validate the equations I use in my MATLAB codeThis code uses the Maple kernel of MATLAB to validate the equations (so you don't need to have Maple on your machine anymore)Not a very complex code but can become very handy when you are working with complex and long equations it can show you the functions in a human readable way (true mathematical notation) so you can see your equation visually and check itThis function uses the Maple's LaTEX function and MATLAB's TEX render engine to provide nice formulaPlease send me an email if you should have any question or want to report a bug
The input to this function is a matlab/simulink function name, such as 'rand' as a string. The function checks the version in which the input function was introduced. This function also accepts a group as input functions to check. See the following examples: Example 1: >> when('rand') ## rand is a built-in function (Introduced before R2006a) Example 2: func_name = {'rand','plot','grid','findstr','weboptions'}; when(func_name) ## rand is a built-in function (Introduced before R2006a) ## plot is a built-in function (Introduced before R2006a) ## grid is a Matlab function or an ordinary m-file (Introduced before R2006a) ## findstr is a built-in function (Introduced before R2006a) ## weboptions is a Matlab function or an ordinary m-file (Introduced in R2014b)
Set default arguments for use in function, without having to code the switch-case blocks. Code is quite trivial, but it saves me some time coding.
s = VALIDATEDINPUT(prompt,'s',validStrings) will process the input S using s = validatestring(S,validStrings).k = VALIDATEDINPUT(prompt,classes,attributes) checks the input A using validateattributes(A,classes,attributes).k = VALIDATEDINPUT(prompt,validationFcn) checks the input using the provided validationFcn.If the user input provided at the prompt is invalid, the user will be informed of the reason why and re-prompted until a valid input is given.
Resnet50, densnet201, resnet18, vgg16, exception net, test network are pre-trained models with cross-validation Matlab code. all evaluation metrics are includedhttps://www.youtube.com/watch?v=bjBs4lBFqBU&list=PLAI6JViu7XmcKQpCISPLATV7jkuYRhMsB&index=19&t=2shttps://www.youtube.com/watch?v=tZn6f40Kjcw&list=PLAI6JViu7XmcKQpCISPLATV7jkuYRhMsB&index=20&t=0s
Routines for computation of Weber's parabolic cylinder functionsand their derivatives are provided for both moderate and great values of the argument. Standard, real solutions are considered. Tables of values are included. Documentation in pdf format is added.
fieldfun: Apply a function to the matching fields of structures SummaryS = fieldfun(fun,S1,...,SN) passes the values for each field in structures S1,...,SN to function fun and returns the result in scalar structure S. Each field F in S, i.e. S.(F), is the result of fun(S1.(F),...,SN.(F)).fieldfun allows the organization of data by structure and field name while allowing the data to be easily processed according to the semantically meaninful fields, improving code readability. When only one structure is supplied, fieldfun can also be used as an alternative to structfun, the difference being that the output of structfun is an array, while fieldfun returns a structure, retaining the input format, again improving readability.Inputsfun is either a function handle or a text scalar giving the function's name or operator. The function must take N input arguments, i.e. equal to the number of input structures, and return a value. fun is called once for each field F in S1,...,SN.S1 is a scalar structure or array of structures.S2,...,SN are scalar structures, arrays of structures, or variables of any other class. If S2,...,SN are structures, their fields and field order must match S1. If S2,...,SN are not structures, then they are converted to structures, with the value being assigned to each field.OutputS is a scalar structure with the same fields and field order as S1. The value of each field F in S, i.e. S.(F), is the result of fun(S1.(F),...,SN.(F)).ExampletreatmentGroup(1) = struct( 'name', "John", 'age', 30, 'vaccinated', true );treatmentGroup(2) = struct( 'name', "Jane", 'age', 80, 'vaccinated', false );controlGroup = struct( 'name', "Jim", 'age', 50, 'vaccinated', true );allParticipants = fieldfun( @horzcat, treatmentGroup, controlGroup )allParticipants = struct with fields: name: ["John" "Jane" "Jim"] age: [30 80 50] vaccinated: [1 0 1]More examples available in examples.mlx / examples.pdf.Compatibility, License and CitationCreated in 2022b. Compatible with MATLAB release 2019b and later. Compatible with all platforms.Published under MIT License (see LICENSE.txt).Please cite George Abrahams (https://github.com/WD40andTape/fieldfun, https://www.linkedin.com/in/georgeabrahams).
Argument tab-completion occur when the user presses the key following the function name in the Command Window. The list of available/possible arguments is then presented in a popup window. TABCOMPLETE modifies the [matlabroot '/toolbox/local/TC.xml'] file to set/unset the tab-completion definition of the specified function. Note: changes take effect only after a Matlab restart. TABCOMPLETE(funcName, argType1, argType2, ...) sets the tab-completion list for function arguments 1, 2, etc. argType can be one of these pre-defined keywords: - 'var' - list of current workspace variables - 'fun' - list of accessible functions - 'subfun' - list of accessible sub-functions - 'dir' - list of accessible folders (directories) - 'file' - list of accessible files (of any type) - 'mfile' - list of accessible *.m files (Matlab functions) - 'matfile' - list of accessible *.mat files (Matlab data) - 'figfile' - list of accessible *.fig files (figures) - 'mdlfile' - list of accessible *.mdl files (Simulink models) - 'mcospkg' - list of accessible MCOS class packages (R2010a+) - 'mcosclass' - list of accessible MCOS classes (R2010a+) - 'messageid' - list of accessible error/warning message IDs (R2011b+) - (if none of the above is specified, 'subfun' is set automatically) And in addition to the pre-defined kewords: - additional string value(s) that will be added to the pop-up list Multiple types for the same argument can be specified: - as a cell array - example: {'var','file','on','off'} - as a space-separated string - example: 'var file on off' The last argType specified will apply for all subsequent arguments. The last argType may be '' (empty string) to indicate the end of tab-completed args. The last argType does *NOT* accept additional string values like the rest of the arguments. TABCOMPLETE(funcName,'') removes all arg tab-completions for funcName (this is an immediate corollary of the previous paragraph). definitions=TABCOMPLETE (without any arguments) returns a structure array listing all the current tab-completion definitions. definitions=TABCOMPLETE(funcName) returns a structure listing the tab-completion definition for the specified function (if existing). definitions=TABCOMPLETE(...) returns a structure array listing all tab-completion definitions BEFORE their modification by TABCOMPLETE. Examples: tabcomplete('addpath','dir') % sets multiple folder completions tabcomplete('edit','file fun') % sets multiple file/func completions tabcomplete('cd','dir','') % sets a single-arg folder completion tabcomplete('save','matfile',{'var','-struct','-regexp'}) => *.mat followed by multiple variable-names or '-struct'/'-regexp' tabcomplete('myFunc','') % removes myFunc's arg tab-completions defs = tabcomplete('cd') % returns 'cd' function's tab-completions defs = tabcomplete % returns all currently-defined tab-completionsWarning: This code heavily relies on undocumented and unsupported Matlab functionality. It works on Matlab 7+, but use at your own risk!Technical explanation: A technical explanation of the code in this utility can be found on http://undocumentedmatlab.com/blog/setting-desktop-tab-completions/ Bugs and suggestions: Please send to Yair Altman (altmany at gmail dot com)
This is a MATLAB routine for evaluating the Mittag-Leffler function with two parameters (sometimes also called generalized exponential function). The Mittag-Leffler function with two parameters plays an important role and appears frequently in solutions of fractional differential equations (i.e. differential equations containing fractional derivatives). USAGE:MLF(alpha,beta,Z,P) is the Mittag-Leffler function E_{alpha,beta}(Z) evaluated with accuracy 10^(-P) for each element of Z.Update 2009-03-25:(1) Now Z can also be a two-dimensional array.(2) Addressed the issue reported by Li Jackie. It was caused by rounding errors during computations. Update 2012-09-07:(1) Addressed the potential issue reported by Brian Bigler. (2) Code clean up.
Occasionally you need only the kth output argument of a MATLAB function, where k>1. This function OUTSELECT provides this facility as a 'wrapper' around any other function. It can evaluate and return arguments immediately, or create a new callable function.For example:>> str = 'deacb'; [s,idx] = sort(str)s =abcdeidx = 3 5 4 1 2>> [idx,s] = outselect([2 1],@sort,str)idx = 3 5 4 1 2s =abcde>> argmin = outselect(2,@min);>> argmin(str) ans = 3
The Lambert package contains a function (wapr) for calculating real values of the Lambert W function, as well as a test module for testing wapr against high precision results.Note: The Symbolic Math Toolbox already contains Maple's implementation of the W function. The Maple version accepts complex arguments, and gives results for complex branches of W.Syntax:[w,nerror] = wapr(x,nb,l,m);wherew = output, W(x);nerror = error flag, 0 (no errors), or 1 (error);x = argument of W;nb = branch (0 for upper branch - default, anything else for the lower branch);l ~= 1, argument x is actual value for which W is desired (default); = 1, argument x is positive offset from -exp(-1);m = 1, print error/information messages, ~= 1, don't print anything (default).
These tools effect image blending and masking functionality common in image manipulation applications such as GIMP, Krita, or Photoshop. For a layered image composition GUI based on this functionality, see the parent toolbox linked below.================== BLENDING FUNCTION ==================IMBLEND() can blend images or imagesets as one would blend layers in GIMP or Photoshop. See 'help imblend'I assert that if nothing else, IMBLEND() stands as the single most comprehensive collection and demonstration of blend mode math from GIMP, ImageMagick, Photoshop, Krita, and elsewhere.Inputs are image arrays of same H,V dimension; both can be single images or 4-D imagesets of equal length. -- Mismatches of dimensions 1:2 are not supported. Use IMRESIZE, IMCROP, or PADARRAY to enforce desired colocation of layer content.-- Mismatches of dimension 3:4 are handled by array expansion. User can optionally specify compositing method independently of the blend method.Unlike other image manipulation software, most blend and composition modes have been made parametric. This useful feature may allow the user to tailor the influence of blends in a manner which cannot be acheived using mixdown opacity, or control density/thresholding behavior in composition modes. See the synopsis for details.This collection of blend modes is comprehensive; if a mode is not on this list, it is likely equivalent to one of the modes that is. The list of supported mode synonyms is in the synopsis.Submission thumbnail shows contour plots for the majority of the non-component blend modes. Included in the zip file is a PDF containing this sheet as well as parameter sweeps and documentation of mathematical properties and relationships among modes.COMPOSITION MODES: gimp compatibility (default)translucentdissolve (8 variants)src over src atop src in src outdst overdst atop dst in dst outxorBLEND MODES:██ Bidirectional Modes==== Contrast & Mixing ====softlight (5 variants)overlayhard lightlinear lightvivid lighteasy lightflat light (3 variants)mean light (2 variants)super lightstar lightmoon light (2 variants)pin lighthard mix (3 variants)fog lightenfog darken==== Penumbrae ====penumbra A (3 variants)penumbra B (3 variants)==== Quadratics ====glowheatreflectfreezefrectreezehelowgleat==== Mean-Scaled ====scale add scale mult contrast ██ Unidirectional Complementary Pairs==== Dodges & Burns ====color dodge & burnpoly dodge & burnlinear dodge & burneasy dodge & burngamma dodge & burnsuau dodge & burnmaleki dodge & burn==== Hybrid Glow & Shadow ====flat glow & shadowmean glow & shadowstar glow & shadowmoon glow & shadow (2 variants)==== Krita/EB Assortment ====tint & shadelighteneb & darkeneb██ Relationallighten RGBdarken RGBlighten Ydarken Ysaturatedesaturatemost satleast satnearfarreplace preserve██ Mathematic & Technicalmultiplyscreendivideadditionsubtractionbleachstaindifferencephoenixexclusion negationsqrtdiffaverageagmgeometricghmharmonicinterpolatehard intpnormarctancurvesgammalightgammadarkgrain extractgrain merge██ Mesh Modesmeshbombbomblockedhard bomb██ Selected Mesh Presetslcd+4 others██ Modulo Modesmodmod shiftmod dividecmodcmod shiftcmod divide██ Componenthuesaturationcolor (12 variants)valueluma (2 variants)lightnessintensitytransfer inchan>outchan (directly transfer any channel to another)permute inchan>H (rotate hue)permute inchan>HS (rotate hue and blend saturation)██ Specialty Modesrecolor {colormodel}blurmap {kernel}================== MASKING FUNCTION ==================Also included is REPLACEPIXELS() which effects an opacity blending similar to GIMP's 'Layer Mask' functionality. Accepts two input images and a mask. Foreground image may be replaced by a color triplet for convenience. REPLACEPIXELS() supports multichannel and multiframe masks, and can support NaN throughput if mask is logical. REPLACEPIXELS() can optionally perform masking in linear RGB.Archive includes support functions for image conversion and typecasting. IP Toolbox is not required.Documentation with commentary, example code, and input/output images is available here:http://mimtdocs.rf.gd/manual/html/imblend.htmlThis is part of my image manipulation toolbox:http://www.mathworks.com/matlabcentral/fileexchange/53786-image-manipulation-toolbox
ELLIPTIC12i evaluates the Incomplete Elliptic Integrals of the First, Second Kind and Jacobi's Zeta Function for the complex value of phase U. Parameter M must be in the range 0 <= M <= 1. [Fi,Ei,Zi] = ELLIPTIC12i(U,M,TOL) where U is a complex phase in radians, M is the real parameter and TOL is the tolerance (optional). Default value for the tolerance is eps = 2.220e-16.ELLIPTIC12i uses the function ELLIPTIC12 to evaluate the values of corresponding integrals.See also ELLIPKE, ELLIPJ, ELLIPTIC12.
InputPreprocessor provides an alternate interface to the class, inputParser, together with the function, validateattributes. It exposes most of the functionalities of theese two. In addition to the constraints (attributes) of validateattributes the user can add new constraints.The goal is that InputPreprocessor shall help the user to make fewer trivial mistakes and write better code. That is, write code that is easier to understand and maintain. Furhermore, the code shall be an essential part of the documentation of the input arguments.InputPreprocessor is not for all functions/methods. Especially, it should not be used when speed is a critical isssue. Syntax:ipp = InputPreprocessor( CA );ipv = ipp.parse( input_argument_list );where CA is a cell array with one row for each input argument of the function/method. The columns contain:1. integer {1,2,3} chooses between: {addRequired,addOptional,addParamValue} 2. the name of the input argument3. the default value of the input argument4. the names of the classes that are allowed for the value 5. constraints on the value of the input argument ipv is a name/value structure, which holds the complete and validated input data.Documentation: InputPreprocessor_demo.html, which is generated by PUBLISH, discusses and demonstrate the use and behaviour of InputPreprocessor. The code is commented. However, there is no manual. InputPreprocessor is a class under construction. However, it allready helps me make fewer trivial mistakes and write better code. I think it is worth while to develop it further. I would appreciate comments and critisism on this contribution. I have no experience of other modern programming environment. I fear I'm inventing a wheel and that the current version of InputPreprocessor is more like a square.
cache_resutls will evaluate a specified function with the provided arguments, then save the results to disk in a file named according to the first argument. On a subsequent call, it will check for such a file, and, if the arguments match, return the result read from file instead of re-evaluating the function. In a situation where the same function is being evaluated on the same data in multiple places (or mulitple times), and where the evaluation is at least moderately computationally expensive, cache_results can be used as a transparent replacement that will avoid redundant computations.When the first argument is a string (for instance, a file name), this name is used (with small modifications) as the name of the cached results file (within a specific cache directory). When the first argument is some other Matlab type, it is converted into a hexadecimal hash (using Jan Simon's DataHash) which is then used as the cache file name.Although (sometimes) only the first function argument is used to construct the cache file name, all the arguments to the function are recorded in the file, along with the corresponding output. When a cache file is found, cache_results then performs an exact comparison of all the arguments (as recorded in the cache file) with all the arguments provided for the current invocation, and only uses the cached result if the arguments match. If no match is found, the provided function is executed. This new result is then added to the cache file (along with the distinct set of arguments), so that in future both results will be returned from cache. Thus, while individual cache files distinguish only the first argument, the system can handle any number of different argument sets associated with this first argument. However, the search through different argument sets within a cache file is linear (at present), so the most efficient way to use the function.While largely transparent, using a results cache of this kind has a few drawbacks. If the function does not give deterministic results given its input arguments, then caching the result will "freeze" the output, changing its behavior. If the first argument refers to a file on disk, but that input file itself is changed, cache_results will not know to re-evaluate the function on the new file. If the function itself is changed (so that even when evaluated with the same input arguments, its result will be different), cache_results will still return the cached value. There's some code within the function to check the modification date of both cache file and function which could possibly force a recalculation when the function is modified, but this behavior is currently disabled.See http://www.ee.columbia.edu/~dpwe/resources/matlab/cache_results/ .
FARG parses an M-file (function or script) searching for function tags and lists their exact, literal syntax.in addition, FARG displays a wide variety of file statistics.currently, these functions are detected and listed- main function- subfunctions- nested functions- anonymous functions- eval class calls- unresolved callswhitespaces and continuation statements are removed for better readability of the function syntax.if the lex parser encounters fatal errors, it will stop processing and print a list of the offending syntax.tested under r2007a, older version 7 systems might work as well.see:>> help fargand the accompanying published M-file for information and a few self-explanatory examples.
Matlab function for pre-trained model Resnet18 with cross-validation https://www.mathworks.com/help/deeplearning/ug/pretrained-convolutional-neural-networks.htmlfor more description about this function see this videohttps://youtu.be/iuX34ku2CbMhttps://youtu.be/eX40gx_q93Y