├── stats ├── mpbdv.m ├── graystep.m ├── zeroOneLossFn.m ├── addOnes.m ├── sigmoid.m ├── roundto.m ├── factorialln.m ├── softThreshold.m ├── softmaxLog.m ├── squaredErrorLossFn.m ├── convertLabelsTo01.m ├── drange.m ├── convertLabelsToPM1.m ├── flipBits.m ├── nansumPMTK.m ├── randpd.m ├── softeye.m ├── quantilePMTK.m ├── digamma.m ├── pinvPMTK.m ├── reshapePMTK.m ├── softmaxPmtk.m ├── stackedRandpd.m ├── nchoosekln.m ├── standardizeCols.m ├── splineBasis.m ├── satDataLoad.m ├── nanmeanPMTK.m ├── deflation.m ├── fisheririsLoad.m ├── mkUnitNorm.m ├── logdet.m ├── mkUnitVariance.m ├── centerCols.m ├── readlines.m ├── requireImageToolbox.m ├── requireStatsToolbox.m ├── requireOptimToolbox.m ├── requireBioinfoToolbox.m ├── normalizeLogspace.m ├── matrixEntropy.m ├── partitionedCov.m ├── makeGrid2d.m ├── sigmoidTimesGauss.m ├── powerMethod.m ├── rescaleData.m ├── dblquadrep.m ├── randsplit.m ├── sumOver.m ├── mutualInfoClassFeaturesBinary.m ├── nanvarPMTK.m ├── partitionedSum.m ├── preprocessorCreate.m ├── mk_multi_index.m ├── sqDistance.m ├── text2stream.m ├── makePolyData.m ├── bestPermutation.m ├── make2dData.m ├── createXORdata.m ├── normalize.m ├── partitionData.m ├── classConfMat.m ├── makeModelSpace.m ├── preprocessorApplyToTest.m ├── oneStdErrorRule.m ├── covcond.m ├── degexpand.m ├── crossProduct.m ├── polyBasis.m ├── multiSigmoid.m ├── greedySpan.m ├── computeCounts.m ├── mkStochastic.m ├── subsets1.m ├── dblquadvec.m ├── minK.m ├── partitionedMean.m ├── polyDataMake.m ├── numericalIntegral.m ├── ROCcurve.m ├── preprocessorApplyToTrain.m ├── paracylTest.m ├── cvEstimate.m └── Kfold.m ├── matlabTools.zip ├── util ├── repmatC.mexglx ├── repmatC.mexw32 ├── cellwrap.m ├── iseven.m ├── repmatC.m ├── insertEnd.m ├── subc.m ├── isdiag.m ├── islower.m ├── isupper.m ├── sortidx.m ├── isrowvec.m ├── err.m ├── iscolvec.m ├── removeEmpty.m ├── pathFolders.m ├── safeStr.m ├── datestring.m ├── systemf.m ├── restoreSeed.m ├── dots.m ├── issubset.m ├── filterCell.m ├── wrap.m ├── insertFront.m ├── minidx.m ├── sortfun.m ├── squeezeFirst.m ├── maxidx.m ├── sparsevec.m ├── squeezePMTK.m ├── shuffleRows.m ├── cellfunNonEmpty.m ├── idim.m ├── structSubset.m ├── unionPMTK.m ├── pclear.m ├── uniquePMTK.m ├── utri.m ├── endswith.m ├── printvec.m ├── repmatPMTK.m ├── firstTrue.m ├── removeDuplicates.m ├── cellfunR.m ├── powerset.m ├── removeNaNrows.m ├── startswith.m ├── onesPMTK.m ├── isSubstring.m ├── mat2cellRows.m ├── moveFields.m ├── findString.m ├── removeFields.m ├── allSameTypes.m ├── intersectPMTK.m ├── removeExtraSpaces.m ├── horzStackPages.m ├── vertStackPages.m ├── argmax.m ├── seteq.m ├── assertTrue.m ├── insertBlankCells.m ├── partitionCell.m ├── catStruct.m ├── cellfind.m ├── padOnes.m ├── padZeros.m ├── google.m ├── argmin.m ├── addToStruct.m ├── removeNonPrintedChars.m ├── fnameOnly.m ├── fnjoin.m ├── textBetween.m ├── interweave.m ├── cellDepth.m ├── cellfuncell.m ├── setdiag.m ├── colvec.m ├── sub.m ├── msxfun.m ├── rowvec.m ├── collapseCell.m ├── insertSingleton.m ├── setdiffPMTK.m ├── setSeed.m ├── ndimsPMTK.m ├── approxeq.m ├── zipmats.m ├── sizePMTK.m ├── createStruct.m ├── unSandwich.m ├── enumerate.m ├── structure.m ├── bsxTable.m ├── isprefix.m ├── prepareArgs.m ├── replicate.m ├── deconstruct.m ├── SetDefaultValue.m ├── protect.m ├── catString.m ├── ind2subv.m ├── nunique.m ├── structvals.m └── extractArgs.m ├── graphics ├── seqlogoLetters.mat ├── pdffigure.m ├── subplot2.m ├── maximizeFigure.m ├── contourShade.m ├── hsvrand.m ├── verticalLine.m ├── horizontalLine.m ├── rel2absY.m ├── shade.m ├── vectorToImage.m ├── nsubplots.m ├── rel2absX.m ├── colorbars.m ├── plotColors.m ├── dataWindow.m ├── imageToVector.m ├── plotSurface.m ├── gaussPlot2d.m ├── gridSpace.m ├── plotConvDiagnostics.m ├── plotmarkers.m ├── plotContour.m ├── printPmtkFigure.m ├── plotPatches.m ├── pdfcrop.m ├── pmtkColors.m ├── rocCurve.m ├── plotCVgrid.m └── image_rgb.m ├── graph ├── parents.m ├── mkChain.m ├── children.m ├── graphRoots.m ├── graphLeaves.m ├── nedges.m ├── allFamilies.m ├── neighbors.m ├── pmtkGraphIsDag.m ├── isTopoOrdered.m ├── ancestors.m ├── isWeaklyConnected.m ├── ndags.m ├── ancestralGraph.m ├── mkTreeDag.m ├── mkSymmetric.m ├── acyclic.m ├── reachability_graph.m ├── moralizeGraph.m ├── minSpanTreePrim.m ├── mkRootedTree.m ├── mkChordal.m ├── mkGrid.m └── dfs_test.m ├── metaTools ├── editc.m ├── hasTag.m ├── htmlBreak.m ├── missingTitleReport.m ├── cfilelist.m ├── cls.m ├── mypath.m ├── allMfilesOnPath.m ├── containingDirectory.m ├── isbuiltin.m ├── removePath.m ├── funcName.m ├── winpath.m ├── dirs.m ├── visdiffOpen.m ├── currentlyOpenFiles.m ├── formatHtmlText.m ├── removeShadows.m ├── findIdenticalShadowedCopies.m ├── providePath.m ├── missingEnds.m ├── deleteIdenticalShadowedCopies.m ├── filenames.m ├── getTagText.m ├── helpline.m ├── removeFromSystemPath.m ├── countLinesOfCode.m ├── currentlyOpenFile.m ├── addtosystempath.m ├── onMatlabPath.m ├── countLinesOfCodeDir.m ├── showFigures.m ├── htmFormatText.m ├── isfunction.m ├── findAllFilesWithTag.m ├── removeComments.m ├── gatherTagText.m ├── previewPublished.m ├── getText.m ├── dirinfo.m ├── showImmediateToolboxDependencies.m ├── getFileModificationDate.m ├── getFileSize.m ├── htmlTagKey.m ├── htmlTagString.m ├── statsToolboxDependencies.m ├── writeText.m ├── searchAndReplaceLine.m ├── convertLinksToHtml.m ├── multiLineString.m ├── compileC.m ├── googleCodeLink.m ├── isEndKeywordMissing.m ├── whoDependsOnToolbox.m ├── shadowFunction.m ├── hideFigures.m └── exportsvn.m ├── oop ├── isproperty.m ├── methodsNoCons.m ├── isclassdef.m ├── localMethods.m ├── protectedMethods.m ├── isabstract.m ├── classesBFS.m ├── getClasses.m └── islocal.m ├── matlabToolsRoot.m ├── README.md └── meta ├── insertCopyrightMatlabTools.m ├── localReports └── matlabToolsSynopses.m ├── changeCopyrightMatlabTools.m └── refreshMatlabToolsZip.m /stats/mpbdv.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murphyk/matlabtools/HEAD/stats/mpbdv.m -------------------------------------------------------------------------------- /matlabTools.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murphyk/matlabtools/HEAD/matlabTools.zip -------------------------------------------------------------------------------- /stats/graystep.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murphyk/matlabtools/HEAD/stats/graystep.m -------------------------------------------------------------------------------- /util/repmatC.mexglx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murphyk/matlabtools/HEAD/util/repmatC.mexglx -------------------------------------------------------------------------------- /util/repmatC.mexw32: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murphyk/matlabtools/HEAD/util/repmatC.mexw32 -------------------------------------------------------------------------------- /graphics/seqlogoLetters.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murphyk/matlabtools/HEAD/graphics/seqlogoLetters.mat -------------------------------------------------------------------------------- /stats/zeroOneLossFn.m: -------------------------------------------------------------------------------- 1 | 2 | % This file is from matlabtools.googlecode.com 3 | 4 | 5 | function L = zeroOneLoss(yhat, ytest) 6 | L = (yhat(:) ~= ytest(:)); 7 | end 8 | -------------------------------------------------------------------------------- /stats/addOnes.m: -------------------------------------------------------------------------------- 1 | function X = addOnes(X) 2 | % Add a column of ones to X 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | X = [ones(size(X, 1), 1), X]; 7 | end 8 | -------------------------------------------------------------------------------- /stats/sigmoid.m: -------------------------------------------------------------------------------- 1 | function p = sigmoid(x) 2 | % Sigmoid function: s(x) = 1 / (1+exp(-x)) 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | p = 1./(1+exp(-x)); 7 | end 8 | -------------------------------------------------------------------------------- /graph/parents.m: -------------------------------------------------------------------------------- 1 | function ps = parents(G, i) 2 | %% Return the list of parents of node i 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | ps = find(G(:, i))'; 7 | end 8 | -------------------------------------------------------------------------------- /util/cellwrap.m: -------------------------------------------------------------------------------- 1 | function c = cellwrap(c) 2 | % Ensure that the input is a cell array 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | if ~iscell(c),c = {c}; end 7 | end 8 | -------------------------------------------------------------------------------- /util/iseven.m: -------------------------------------------------------------------------------- 1 | function b = iseven(a) 2 | % Return true iff the input is an even integer 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | b = mod(a, 2) == 0; 7 | 8 | end 9 | -------------------------------------------------------------------------------- /util/repmatC.m: -------------------------------------------------------------------------------- 1 | function B = repmatC(varargin) 2 | %% A c version of repmat 3 | %PMTKmex 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | B = repmat(varargin{:}); 8 | end 9 | -------------------------------------------------------------------------------- /graph/mkChain.m: -------------------------------------------------------------------------------- 1 | function G = mkChain(T) 2 | % Make a 1D chain-structured graph of length T 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | G = diag(ones(T-1, 1), 1); 7 | end 8 | -------------------------------------------------------------------------------- /stats/roundto.m: -------------------------------------------------------------------------------- 1 | function A = roundto(A, d) 2 | % Round entries of matrix to the specified precision 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | A = round(A./d)*d; 7 | end 8 | -------------------------------------------------------------------------------- /util/insertEnd.m: -------------------------------------------------------------------------------- 1 | function C = insertEnd(element, C) 2 | % Add an element to the end of a cell array 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | C{end+1} = element; 7 | end 8 | -------------------------------------------------------------------------------- /util/subc.m: -------------------------------------------------------------------------------- 1 | function a = subc(b,ndx) 2 | % Subscript the cell array return value of a function directly 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | a = b{ndx}; 7 | 8 | end 9 | -------------------------------------------------------------------------------- /graph/children.m: -------------------------------------------------------------------------------- 1 | function C = children(G, i) 2 | %% Return the indices of a node's children in sorted order 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | C = find(G(i, :)); 7 | end 8 | -------------------------------------------------------------------------------- /stats/factorialln.m: -------------------------------------------------------------------------------- 1 | function L = factorialln(n) 2 | % L(i) = log n(i)! 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | % n! = gamma(n+1) 8 | L= gammaln(n + 1); 9 | end 10 | -------------------------------------------------------------------------------- /stats/softThreshold.m: -------------------------------------------------------------------------------- 1 | function out = softThreshold(x, delta) 2 | % Soft thresholding 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | out = sign(x) .* max(abs(x) - delta, 0); 7 | end 8 | 9 | -------------------------------------------------------------------------------- /stats/softmaxLog.m: -------------------------------------------------------------------------------- 1 | function L = softmaxLog(X,W) 2 | % L(n,:) = log softmax(W * X(n,:)') 3 | eta = X*W; 4 | Z = sum(exp(eta), 2); 5 | nclasses = size(eta,2); 6 | L = eta - repmat(log(Z), 1, nclasses); 7 | end -------------------------------------------------------------------------------- /stats/squaredErrorLossFn.m: -------------------------------------------------------------------------------- 1 | function L = squaredErrorLossFn(yhat, ytest) 2 | L = (yhat - ytest).^2; 3 | %L = (yhat(:) - ytest(:)).^2; 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | end 8 | -------------------------------------------------------------------------------- /util/isdiag.m: -------------------------------------------------------------------------------- 1 | function p = isdiag(M) 2 | % Return true iff the input is a diagonal matrix 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | p = isequal(diag(diag(M)), M); 7 | 8 | 9 | end 10 | -------------------------------------------------------------------------------- /util/islower.m: -------------------------------------------------------------------------------- 1 | function answer = islower(s) 2 | %% Return true iff the input string is all lower case 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | answer = strcmp(s, lower(s)); 7 | 8 | end 9 | -------------------------------------------------------------------------------- /util/isupper.m: -------------------------------------------------------------------------------- 1 | function answer = isupper(s) 2 | %% Return true iff the input string is all upper case 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | answer = strcmp(s, upper(s)); 7 | 8 | end 9 | -------------------------------------------------------------------------------- /util/sortidx.m: -------------------------------------------------------------------------------- 1 | function [perm,val] = sortidx(varargin) 2 | % Return the index permutation that sorts an array 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | [val,perm] = sort(varargin{:}); 7 | end 8 | -------------------------------------------------------------------------------- /graph/graphRoots.m: -------------------------------------------------------------------------------- 1 | function roots = graphRoots(G) 2 | %% Return the roots in a directed graph, (nodes with no parents) 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | roots = find(~any(G, 1)); 7 | end 8 | -------------------------------------------------------------------------------- /stats/convertLabelsTo01.m: -------------------------------------------------------------------------------- 1 | function y = convertLabelsTo01(y) 2 | % Ensure that y(i) is in {0,1} 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | y = canonizeLabels(y); % 1,2 7 | y = y - 1; % 0,1 8 | end 9 | -------------------------------------------------------------------------------- /graph/graphLeaves.m: -------------------------------------------------------------------------------- 1 | function leaves = graphLeaves(G) 2 | %% Return the leaves in a directed graph, (nodes with no children) 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | leaves = find(~any(G, 2)); 7 | end 8 | -------------------------------------------------------------------------------- /metaTools/editc.m: -------------------------------------------------------------------------------- 1 | function editc(files) 2 | % Open all of the specified files for editting 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | for i=1:numel(files) 7 | edit(files{i}); 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /util/isrowvec.m: -------------------------------------------------------------------------------- 1 | function answer = isrowvec(T) 2 | %% Return true if the result is a row vector 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | answer = isvector(T) && size(T, 2) > 1; 8 | 9 | end 10 | -------------------------------------------------------------------------------- /metaTools/hasTag.m: -------------------------------------------------------------------------------- 1 | function found = hasTag(filename, tag) 2 | % Return true if the file has the specified tag. 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | found = ismember(tag, tagfinder(filename)); 7 | end 8 | -------------------------------------------------------------------------------- /metaTools/htmlBreak.m: -------------------------------------------------------------------------------- 1 | function str = htmlBreak(str) 2 | % Convert new line chars to html breaks 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | 8 | str = regexprep(str, '\\n', '
'); 9 | 10 | end 11 | -------------------------------------------------------------------------------- /util/err.m: -------------------------------------------------------------------------------- 1 | function err(ME, message) 2 | % Throw an error as the caller with a custom message 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | throwAsCaller(addCause(MException('Generic:Error', message), ME)); 7 | end 8 | -------------------------------------------------------------------------------- /util/iscolvec.m: -------------------------------------------------------------------------------- 1 | function answer = iscolvec(T) 2 | %% Return true if the result is a column vector 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | answer = isvector(T) && size(T, 1) > 1; 8 | 9 | end 10 | -------------------------------------------------------------------------------- /util/removeEmpty.m: -------------------------------------------------------------------------------- 1 | function c = removeEmpty(c) 2 | % Remove all empty cells from a cell array 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | c = c(~cellfun('isempty', c)); % 'isempty' is faster than @isempty 7 | end 8 | -------------------------------------------------------------------------------- /util/pathFolders.m: -------------------------------------------------------------------------------- 1 | function d = pathFolders(p) 2 | %% Return the folders in a file path 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | sep = ['\', filesep]; 8 | d = tokenize(fileparts(p), sep); 9 | 10 | end 11 | -------------------------------------------------------------------------------- /stats/drange.m: -------------------------------------------------------------------------------- 1 | function y = drange(x, dim) 2 | % Return the range of the data along a specified dimension 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | if nargin < 2, dim = 1; end 7 | y = max(x,[],dim) - min(x,[],dim); 8 | end 9 | -------------------------------------------------------------------------------- /util/safeStr.m: -------------------------------------------------------------------------------- 1 | function s = safeStr(s) 2 | % Change punctuation characters to they print properly 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | s = strrep(s, '\', '/'); 8 | s = strrep(s, '_', '-'); 9 | 10 | end 11 | -------------------------------------------------------------------------------- /stats/convertLabelsToPM1.m: -------------------------------------------------------------------------------- 1 | function y = convertLabelsToPM1(y) 2 | % Ensure that y(i) is in{-1,+1} 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | y = canonizeLabels(y); % 1,2 7 | y = y - 1; % 0,1 8 | y = 2*y-1; % -1,1 9 | end 10 | -------------------------------------------------------------------------------- /util/datestring.m: -------------------------------------------------------------------------------- 1 | function d = datestring() 2 | %% Return a string name based on the current date and time 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | d = datestr(now); d(d ==':') = '_'; d(d == ' ') = '_'; d(d=='-') = []; 7 | end 8 | -------------------------------------------------------------------------------- /stats/flipBits.m: -------------------------------------------------------------------------------- 1 | function yhat = flipBits(y, p) 2 | % Flib bits in binary matrix y with probability p 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | M = rand(size(y)) < p; 8 | yhat = y; 9 | yhat(M) = ~yhat(M); 10 | 11 | end 12 | -------------------------------------------------------------------------------- /graphics/pdffigure.m: -------------------------------------------------------------------------------- 1 | function h=pdffigure(varargin) 2 | % Just like figure, except makes the paper size equal to the figure size 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | h=figure(varargin{:}); 8 | pdfcrop(h); 9 | 10 | end 11 | -------------------------------------------------------------------------------- /util/systemf.m: -------------------------------------------------------------------------------- 1 | function [status, result] = systemf(command,varargin) 2 | % Just like built in system but allows sprintf syntax 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | [status, result] = system(sprintf(command,varargin{:})); 7 | end 8 | -------------------------------------------------------------------------------- /util/restoreSeed.m: -------------------------------------------------------------------------------- 1 | function restoreSeed() 2 | %% Restore the random seed altered by setSeed 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | global RNDN_STATE RND_STATE 7 | randn('state',RNDN_STATE); 8 | rand('state',RND_STATE); 9 | 10 | end 11 | -------------------------------------------------------------------------------- /util/dots.m: -------------------------------------------------------------------------------- 1 | function out = dots(n) 2 | % Print n dots to the console 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | if nargout > 0 7 | out = sprintf('%s', repmat('.', 1,n)); 8 | else 9 | fprintf('%s', repmat('.', 1,n)) 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /util/issubset.m: -------------------------------------------------------------------------------- 1 | function bool = issubset(A, B) 2 | % Return true iff A is a subset of B 3 | % e.g. 4 | % issubset(1:3,1:5) 5 | % ans = 6 | % 1 7 | % 8 | 9 | % This file is from matlabtools.googlecode.com 10 | 11 | bool = all(ismember(A, B)); 12 | 13 | end 14 | -------------------------------------------------------------------------------- /util/filterCell.m: -------------------------------------------------------------------------------- 1 | function [Csmall, idx] = filterCell(Cbig,fn) 2 | % Keep only those elements c, of a cell array for which fn(c) is true 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | idx = find(cellfun(fn, Cbig)); 8 | Csmall = Cbig(idx); 9 | end 10 | -------------------------------------------------------------------------------- /graphics/subplot2.m: -------------------------------------------------------------------------------- 1 | function subplot2(nrows, ncols, i, j) 2 | % function subplot2(nrows, ncols, i, j) 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | sz = [nrows ncols]; 8 | k = sub2ind(sz(end:-1:1), j, i); 9 | subplot(nrows, ncols, k); 10 | 11 | end 12 | -------------------------------------------------------------------------------- /oop/isproperty.m: -------------------------------------------------------------------------------- 1 | function p = isproperty(class,prop) 2 | % Return true iff a specified class has a specific property 3 | % PMTKneedsMatlab 2008 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | props = properties(class); 8 | p = ismember(prop,props); 9 | end 10 | -------------------------------------------------------------------------------- /util/wrap.m: -------------------------------------------------------------------------------- 1 | function v = wrap(u,N) 2 | % Wrap a vector of indices around a torus 3 | % v = wrap(u,N) 4 | % 5 | % e.g., wrap([-1 0 1 2 3 4], 3) = 2 3 1 2 3 1 6 | 7 | % This file is from matlabtools.googlecode.com 8 | 9 | 10 | v = mod(u-1,N)+1; 11 | 12 | end 13 | -------------------------------------------------------------------------------- /matlabToolsRoot.m: -------------------------------------------------------------------------------- 1 | function r = matlabToolsRoot() 2 | %% Return the root matlabTools directory 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | w = which(mfilename()); 7 | if w(1) == '.' 8 | w = fullfile(pwd, w(3:end)); 9 | end 10 | r = fileparts(w); 11 | end 12 | -------------------------------------------------------------------------------- /oop/methodsNoCons.m: -------------------------------------------------------------------------------- 1 | function m = methodsNoCons(classname) 2 | % Return all of the methods of the class except the constructor 3 | % PMTKneedsMatlab 2008 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | m = methods(classname); 8 | m = setdiff(m,classname); 9 | end 10 | -------------------------------------------------------------------------------- /util/insertFront.m: -------------------------------------------------------------------------------- 1 | function C = insertFront(element, C) 2 | % Add an element to the front of a cell array 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | if size(C, 1) >= size(C, 2) 7 | C = [element; C]; 8 | else 9 | C = [element, C]; 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /util/minidx.m: -------------------------------------------------------------------------------- 1 | function [idx, val] = minidx(varargin) 2 | % Return the linear index of the minimum value 3 | % Same as built in min but with the order of the outputs reversed. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | [val,idx] = min(varargin{:}); 8 | end 9 | -------------------------------------------------------------------------------- /util/sortfun.m: -------------------------------------------------------------------------------- 1 | function x = sortfun(f, x) 2 | % Sort a cell array by some function of its elements 3 | % e.g. sortfun(@(x)numel(x),C) sorts C by the number of elements in each cell. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | x = x(sortidx(cellfun(f, x))); 8 | end 9 | -------------------------------------------------------------------------------- /util/squeezeFirst.m: -------------------------------------------------------------------------------- 1 | function A = squeezeFirst(A) 2 | %% Squeeze only the first dimension 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | if size(A, 1) > 1 8 | return; 9 | end 10 | sz = [size(A), 1]; 11 | A = reshape(A, sz(2:end)); 12 | 13 | 14 | end 15 | -------------------------------------------------------------------------------- /metaTools/missingTitleReport.m: -------------------------------------------------------------------------------- 1 | function R = missingTitleReport() 2 | % Generate a list of PMTK3 demos that are missing titles. 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | demos = processExamples({}, {}, 0, false)'; 7 | R = filterCell(demos, @(f)isempty(help(f))); 8 | end 9 | -------------------------------------------------------------------------------- /util/maxidx.m: -------------------------------------------------------------------------------- 1 | function [idx, val] = maxidx(varargin) 2 | %% Return the linear index of the maximum value 3 | % Same as built in max but with the order of the outputs reversed. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | [val,idx] = max(varargin{:}); 9 | end 10 | -------------------------------------------------------------------------------- /stats/nansumPMTK.m: -------------------------------------------------------------------------------- 1 | function s = nansumPMTK(X, dim) 2 | %% Replacement for the stats toolbox nansum function 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | X(isnan(X)) = 0; 8 | if nargin < 2 9 | s = sum(X); 10 | else 11 | s = sum(X, dim); 12 | end 13 | 14 | end 15 | -------------------------------------------------------------------------------- /util/sparsevec.m: -------------------------------------------------------------------------------- 1 | function S = sparsevec(ndx, vals, len) 2 | %% Create a sparse vector of length len, with S(ndx) equal to vals 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | if nargin < 3, len = max(ndx); end 8 | S = sparse(ndx, 1, vals, len, 1)'; 9 | end 10 | 11 | 12 | -------------------------------------------------------------------------------- /util/squeezePMTK.m: -------------------------------------------------------------------------------- 1 | function A = squeezePMTK(A) 2 | %% Same as built in squeeze function except it squeezes even rowvecs 3 | % into colvecs. 4 | % 5 | %% 6 | 7 | % This file is from matlabtools.googlecode.com 8 | 9 | A = squeeze(A); 10 | if isvector(A) 11 | A = A(:); 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /metaTools/cfilelist.m: -------------------------------------------------------------------------------- 1 | function cfiles = cfilelist(directory) 2 | % Return a list of all .c and .cpp files in the specified directory structure 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | if nargin == 0, directory = pwd(); end 7 | cfiles = filelist(directory, {'*.c', '*.cpp'}); 8 | end 9 | -------------------------------------------------------------------------------- /util/shuffleRows.m: -------------------------------------------------------------------------------- 1 | function [X, y] = shuffleRows(X, y) 2 | % Randomly shuffle the rows of a matrix 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | n = size(X, 1); 7 | perm = randperm(n); 8 | X = X(perm, :); 9 | if nargin == 2 10 | y = y(perm, :); 11 | end 12 | 13 | end 14 | -------------------------------------------------------------------------------- /util/cellfunNonEmpty.m: -------------------------------------------------------------------------------- 1 | function C = cellfunNonEmpty(fn, C) 2 | %% Apply a function to the non-empty elements of C 3 | % always returns a cell array 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | ndx = ~cellfun('isempty', C); 9 | 10 | C(ndx) = cellfuncell(fn, C(ndx)); 11 | end 12 | -------------------------------------------------------------------------------- /util/idim.m: -------------------------------------------------------------------------------- 1 | function A = idim(A, i, j) 2 | %% Interchange dimensions i and j in multidimentional array A 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | perm = 1:max(max(ndims(A), i), j); 8 | perm(i) = j; 9 | perm(j) = i; 10 | 11 | A = permute(A, perm); 12 | 13 | 14 | end 15 | -------------------------------------------------------------------------------- /util/structSubset.m: -------------------------------------------------------------------------------- 1 | function S = structSubset(S, fields) 2 | %% Return a struct identical to S except that it has only the specified fields 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | 8 | S = rmfield(S, setdiff(fieldnames(S), fields)); 9 | S = orderfields(S); 10 | 11 | end 12 | -------------------------------------------------------------------------------- /util/unionPMTK.m: -------------------------------------------------------------------------------- 1 | function U = unionPMTK(A, B) 2 | %% Return the union of two sets of positive integers faster than built in union. 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | C = false(max(max(A), max(B)), 1); 7 | C(A) = true; 8 | C(B) = true; 9 | U = find(C); 10 | end 11 | -------------------------------------------------------------------------------- /util/pclear.m: -------------------------------------------------------------------------------- 1 | function pclear(nsecs) 2 | % Used by runDemos - pause for nsecs and then clear and close figures 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | if(nargin == 0) 7 | nsecs = 1; 8 | end 9 | pause(nsecs); 10 | clear; 11 | close all; 12 | evalin('base','clear'); 13 | end 14 | -------------------------------------------------------------------------------- /util/uniquePMTK.m: -------------------------------------------------------------------------------- 1 | function B = uniquePMTK(A) 2 | %% Return the unique positive integers in A faster than the built in unique 3 | % always returns a row vector 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | bits = false(max(A), 1); 8 | bits(A) = true; 9 | B = find(bits)'; 10 | end 11 | 12 | -------------------------------------------------------------------------------- /metaTools/cls.m: -------------------------------------------------------------------------------- 1 | %% Clear and close everything 2 | 3 | % This file is from matlabtools.googlecode.com 4 | 5 | close all; 6 | close all hidden; 7 | fclose all; 8 | clear all 9 | clear classes; 10 | clear global; 11 | clear java; 12 | dbclear if warning; 13 | try 14 | dbquit('all'); 15 | catch 16 | end 17 | clc; 18 | -------------------------------------------------------------------------------- /graph/nedges.m: -------------------------------------------------------------------------------- 1 | function n = nedges(G, isdirected) 2 | %% Return the number of edges in the graph G 3 | % does not inlcude self loops 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | G = setdiag(G, 0); 8 | if isdirected 9 | n = sum(G(:)); 10 | else 11 | n = sum(colvec(triu(G))); 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /util/utri.m: -------------------------------------------------------------------------------- 1 | function ndx = utri(d) 2 | % Return the indices of the upper triangluar part of a square d-by-d matrix 3 | % Does not include the main diagonal. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | ndx = ones(d*(d-1)/2,1); 8 | ndx(1+cumsum(0:d-2)) = d+1:-1:3; 9 | ndx = cumsum(ndx); 10 | 11 | end 12 | -------------------------------------------------------------------------------- /graphics/maximizeFigure.m: -------------------------------------------------------------------------------- 1 | function maximizeFigure 2 | scrsz = get(0,'ScreenSize'); 3 | %Borders 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | left = 10; right = 10; 8 | lower = 50; upper = 125; 9 | set(gcf,'Position',[left,lower,scrsz(3)-left-right, scrsz(4)-lower-upper]); 10 | end 11 | -------------------------------------------------------------------------------- /util/endswith.m: -------------------------------------------------------------------------------- 1 | function tf = endswith(str, suffix) 2 | % Return true if the string ends in the specified suffix 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | n = length(suffix); 8 | if length(str) < n 9 | tf = false; 10 | else 11 | tf = strcmp(str(end-n+1:end), suffix); 12 | end 13 | 14 | end 15 | -------------------------------------------------------------------------------- /util/printvec.m: -------------------------------------------------------------------------------- 1 | function printvec(x, dp) 2 | % Print a vector of numbers to a fixed number of decimal places 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | if nargin < 2, dp = 3; end 7 | str = sprintf('%s10.%df\n', '%', dp); 8 | for i=1:length(x) 9 | fprintf(str, x(i)) 10 | end 11 | fprintf('\n'); 12 | end 13 | -------------------------------------------------------------------------------- /util/repmatPMTK.m: -------------------------------------------------------------------------------- 1 | function T = repmatPMTK(T, sizes) 2 | % Like the built-in repmat, except repmatPMTK(T,n) == repmat(T,[n 1]) 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | 8 | if length(sizes)==1 9 | T = repmatC(T, [sizes 1]); 10 | else 11 | T = repmatC(T, sizes(:)'); 12 | end 13 | 14 | end 15 | -------------------------------------------------------------------------------- /graphics/contourShade.m: -------------------------------------------------------------------------------- 1 | function h = contourShade(X, Y, Z, C, varargin) 2 | % Just like countourf but with a better interface. 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | [junk1, h, junk2] = contourf(X, Y, Z, C); 8 | if nargin > 4 9 | set(h, varargin{:}); 10 | end 11 | 12 | end 13 | -------------------------------------------------------------------------------- /metaTools/mypath.m: -------------------------------------------------------------------------------- 1 | function p = mypath() 2 | % Return a list of all non-built-in directories on your matlab path 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | p = tokenize(path, ';'); 7 | p = p(~strncmp(matlabroot, p, length(matlabroot))); 8 | p = filterCell(p, @(s)~isSubstring('.svn', s)); 9 | p = [p; pwd]; 10 | end 11 | -------------------------------------------------------------------------------- /util/firstTrue.m: -------------------------------------------------------------------------------- 1 | function idx = firstTrue(boolarray) 2 | % Returns the linear index of the first true element found 3 | % or 0 if none found. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | 9 | idx = find(boolarray); 10 | if ~isempty(idx); 11 | idx = idx(1); 12 | else 13 | idx = 0; 14 | end 15 | 16 | end 17 | -------------------------------------------------------------------------------- /util/removeDuplicates.m: -------------------------------------------------------------------------------- 1 | function C = removeDuplicates(C) 2 | %% Like built in unique function but does alter the order by sorting 3 | % Keeps only the first occurence of each unique element. 4 | %% 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | C(setdiffPMTK(1:numel(C), argout(2, @unique, C, 'first'))) = []; 9 | end 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | matlabtools 2 | =========== 3 | 4 | Matlab tools (from code.google.com/p/matlabtools/). 5 | As of 24 October 2010, all matlabTools code is now included directly in PMTK in order to make it easier to maintain consistency (so users don't have to do an svn update on two sites). So this site is no longer being maintained and should not be used. 6 | -------------------------------------------------------------------------------- /stats/randpd.m: -------------------------------------------------------------------------------- 1 | function M = randpd(d) 2 | % Create a random positive definite matrix of size d by d 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | A = randn(d); 8 | M = A*A'; 9 | while ~isposdef(M) % check to avoid returning a matrix whose logdet is < eps 10 | M = M + diag(0.001*ones(1,d)); 11 | end 12 | 13 | end 14 | -------------------------------------------------------------------------------- /stats/softeye.m: -------------------------------------------------------------------------------- 1 | function M = softeye(K, p) 2 | % Make a stochastic matrix with p on the diagonal, and the remaining mass distributed uniformly 3 | % 4 | % M is a K x K matrix. 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | 9 | M = p*eye(K); 10 | q = 1-p; 11 | for i=1:K 12 | M(i, [1:i-1 i+1:K]) = q / (K-1); 13 | end 14 | -------------------------------------------------------------------------------- /graphics/hsvrand.m: -------------------------------------------------------------------------------- 1 | function colors = hsvrand(N) 2 | % hsvrand Like built-in HSV, except it randomizes the order, so that adjacent colors are dis-similar 3 | % function colors = hsvrand(N) 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | colors = hsv(N); 9 | perm = randperm(N); 10 | colors = colors(perm,:); 11 | 12 | 13 | end 14 | -------------------------------------------------------------------------------- /metaTools/allMfilesOnPath.m: -------------------------------------------------------------------------------- 1 | function m = allMfilesOnPath() 2 | % Return a list of all of the non-built-in .m files on the matlab path 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | p = mypath(); 7 | m = {}; 8 | for i=1:numel(p) 9 | m = [m; mfiles(p{i}, 'topOnly', true)]; %#ok 10 | end 11 | m = unique(m); 12 | 13 | end 14 | 15 | -------------------------------------------------------------------------------- /graph/allFamilies.m: -------------------------------------------------------------------------------- 1 | function fam = allFamilies(G) 2 | %% Return a cell array of the families of every node in the dag G. 3 | % i.e. fam{i} = [parents(G, i), i] 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | nnodes = size(G, 1); 8 | fam = cell(nnodes, 1); 9 | for i=1:nnodes 10 | fam{i} = [parents(G, i), i]; 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /util/cellfunR.m: -------------------------------------------------------------------------------- 1 | function C = cellfunR(fun, C, varargin) 2 | % Recursive version of cellfun, which operates on nested cell arrays 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | if cellDepth(C) < 2 7 | C = cellfuncell(fun, C, varargin{:}); 8 | else 9 | C = cellfuncell(@(cl)cellfunR(fun, cl, varargin{:}), C); 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /util/powerset.m: -------------------------------------------------------------------------------- 1 | function p = powerset(set) 2 | % Return the power set of a set of integers 3 | % e.g. powerset(1:3) = {[],1,2,3,[1,2],[1,3],[2,3],[1,2,3]} 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | p = sortfun(@(x)numel(x), cellfuncell(@(x)set(x),... 8 | num2cell(dec2bin(2^numel(set)-1:-1:0) == '1', 2))); 9 | end 10 | 11 | 12 | -------------------------------------------------------------------------------- /metaTools/containingDirectory.m: -------------------------------------------------------------------------------- 1 | function d = containingDirectory(f) 2 | %% Return the containing directory of the file 3 | % 4 | %% Example 5 | % 6 | % d = containingDirectory('C:\foo\bar\test.txt') 7 | % d = 8 | % 'bar' 9 | %% 10 | 11 | % This file is from matlabtools.googlecode.com 12 | 13 | d = argout(2, @fileparts, (fileparts(f))); 14 | 15 | end 16 | -------------------------------------------------------------------------------- /stats/quantilePMTK.m: -------------------------------------------------------------------------------- 1 | function y = quantilePMTK(X, p) 2 | % Simple replacement for the stats quantile function 3 | % Covers most but possibly not all use cases 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | X = sort(X(:), 1); 8 | n = length(X); 9 | q = [0 100*(0.5:(n-0.5))./n 100]'; 10 | y = interp1q(q, [X; X; X], 100.*p(:)); 11 | 12 | end 13 | -------------------------------------------------------------------------------- /util/removeNaNrows.m: -------------------------------------------------------------------------------- 1 | function A = removeNaNrows(A) 2 | %% Remove NaN rows from the matrix A 3 | % If A is a cell array, do this for every matrix in the array 4 | %% 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | if iscell(A) 9 | A = cellfuncell(@removeNaNrows, A); 10 | return 11 | end 12 | A(any(isnan(A), 2), :) = []; 13 | end 14 | -------------------------------------------------------------------------------- /util/startswith.m: -------------------------------------------------------------------------------- 1 | function tf = startswith(str, prefix) 2 | % Return true iff the string starts with the specified prefix 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | if iscell(str) 8 | tf = cellfuncell(@(s)startswith(s, prefix) , str); 9 | return 10 | end 11 | 12 | 13 | tf = strncmp(str, prefix, length(prefix)); 14 | end 15 | -------------------------------------------------------------------------------- /graphics/verticalLine.m: -------------------------------------------------------------------------------- 1 | function h = verticalLine(xloc, varargin) 2 | % Draws a vertical line at the specified xloc on the current axes. All 3 | % additional args are passed directly to the line function. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | a = axis(); 8 | h = line([xloc, xloc], [a(3), a(4)], varargin{:}); 9 | 10 | end 11 | -------------------------------------------------------------------------------- /metaTools/isbuiltin.m: -------------------------------------------------------------------------------- 1 | function TF = isbuiltin(f) 2 | % Return true iff the specified function is built in. 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | if iscell(f) 7 | TF = cellfun(@isbuiltin, f); 8 | return 9 | end 10 | w = which(f); 11 | TF = ~isempty(w) && ((startswith(w, 'built-in') || (startswith(w,matlabroot())))); 12 | end 13 | -------------------------------------------------------------------------------- /metaTools/removePath.m: -------------------------------------------------------------------------------- 1 | function removePath(p) 2 | % Like builtin rmpath function, but does not issue a warning if p is not on the path. 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | if ischar(p) 7 | p = tokenize(p, ';'); 8 | end 9 | for i=1:numel(p) 10 | if onMatlabPath(p{i}) 11 | rmpath(p{i}) 12 | end 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /stats/digamma.m: -------------------------------------------------------------------------------- 1 | function y = digamma(x) 2 | % Digamma function: d/dx log gamma(x) 3 | % DIGAMMA(X) returns digamma(x) = d log(gamma(x)) / dx 4 | % If X is a matrix, returns the digamma function evaluated at each element. 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | 9 | y = psi(x); % built-in mex function 10 | end 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /util/onesPMTK.m: -------------------------------------------------------------------------------- 1 | function T = onesPMTK(sizes) 2 | % Like the built-in ones, except onesPMTK(k) produces a k*1 vector instead of a k*k matrix 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | if isempty(sizes) 8 | T = 1; 9 | elseif length(sizes)==1 10 | T = ones(sizes, 1); 11 | else 12 | T = ones(sizes(:)'); 13 | end 14 | 15 | end 16 | -------------------------------------------------------------------------------- /graph/neighbors.m: -------------------------------------------------------------------------------- 1 | function ns = neighbors(adj_mat, i) 2 | % NEIGHBORS Find the parents and children of a node in a graph. 3 | % ns = neighbors(adj_mat, i) 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | %ns = myunion(children(adj_mat, i), parents(adj_mat, i)); 9 | ns = uniquePMTK([find(adj_mat(i, :)) find(adj_mat(:, i))']); 10 | 11 | 12 | end 13 | -------------------------------------------------------------------------------- /graphics/horizontalLine.m: -------------------------------------------------------------------------------- 1 | function h = horizontalLine(yloc, varargin) 2 | % Draws a horizontal line at the specified yloc on the current axes. All 3 | % additional args are passed directly to the line function. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | a = axis(); 8 | h = line([a(1), a(2)], [yloc, yloc], varargin{:}); 9 | 10 | end 11 | -------------------------------------------------------------------------------- /stats/pinvPMTK.m: -------------------------------------------------------------------------------- 1 | function B = pinvPMTK(A) 2 | % Same as built-in pinv, but shorter because omits error checking etc 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | [U, S, V] = svd(A, 0); % if m>n, only compute first n cols of U 7 | s = diag(S); 8 | r = sum(s > tol); % rank 9 | w = diag(ones(r,1) ./ s(1:r)); 10 | B = V(:,1:r) * w * U(:,1:r)'; 11 | end 12 | -------------------------------------------------------------------------------- /stats/reshapePMTK.m: -------------------------------------------------------------------------------- 1 | function T = reshapePMTK(T, sizes) 2 | % Like the built-in reshape, except reshapePMTK(T,n) == reshape(T,[n 1]) 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | n = numel(sizes); 8 | if n==0 9 | return; 10 | elseif n == 1 11 | T = reshape(T, [sizes 1]); 12 | else 13 | T = reshape(T, sizes(:)'); 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /util/isSubstring.m: -------------------------------------------------------------------------------- 1 | function tf = isSubstring(a, b, ignoreCase) 2 | % Return true iff the first string is a substring of the second 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | if nargin < 3, ignoreCase = false; end 7 | if ignoreCase 8 | tf = ~isempty(strfind(lower(b),lower(a))); 9 | else 10 | tf = ~isempty(strfind(b,a)); 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /util/mat2cellRows.m: -------------------------------------------------------------------------------- 1 | function c = mat2cellRows(m) 2 | % Place each row of a matrix into its own cell and return the n-by-1 array 3 | % Converts an n-by-d numeric matrix 'm', to an n-by-1 cell array 'c', such 4 | % that c{i} = m(i,:) for all i in 1:size(m,1). 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | c = mat2cell(m, ones(size(m, 1), 1)); 9 | end 10 | -------------------------------------------------------------------------------- /util/moveFields.m: -------------------------------------------------------------------------------- 1 | function [S1, S2] = moveFields(fields, S1, S2) 2 | %% Move fields from struct S1 to struct S2 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | if nargin < 3 8 | S2 = struct(); 9 | end 10 | for i=1:numel(fields) 11 | f = fields{i}; 12 | S2.(f) = S1.(f); 13 | S1 = rmfield(S1, f); 14 | end 15 | 16 | end 17 | -------------------------------------------------------------------------------- /graphics/rel2absY.m: -------------------------------------------------------------------------------- 1 | function yabs = rel2absY(ypos, ax) 2 | % See rel2absX 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | if nargin < 2 7 | ax = gca; 8 | end 9 | ylim = get(ax,'ylim'); 10 | ymin = ylim(1); 11 | ymax = ylim(2); 12 | yscale = ymax - ymin; 13 | axAbs = get(ax,'Position'); 14 | yabs = axAbs(2) + ((ypos-ymin) ./ yscale).*axAbs(4); 15 | end 16 | -------------------------------------------------------------------------------- /stats/softmaxPmtk.m: -------------------------------------------------------------------------------- 1 | function mu = softmaxPmtk(eta) 2 | % Softmax function 3 | % mu(i,c) = exp(eta(i,c))/sum_c' exp(eta(i,c')) 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | tmp = exp(eta); 8 | denom = sum(tmp, 2); 9 | [D, C] = size(eta); %#ok 10 | %mu = tmp ./ repmat(denom, 1, C); 11 | mu = bsxfun(@rdivide, tmp, denom); 12 | 13 | end 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /metaTools/funcName.m: -------------------------------------------------------------------------------- 1 | function name = funcName(fn) 2 | % Just like built in func2str except it removes @() prefixes and () 3 | % suffixes. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | s = func2str(fn); 9 | if startswith(s, '@') 10 | toks = tokenize(s, '()'); 11 | name = toks{3}; 12 | else 13 | name = s; 14 | end 15 | 16 | 17 | 18 | end 19 | -------------------------------------------------------------------------------- /stats/stackedRandpd.m: -------------------------------------------------------------------------------- 1 | function S = stackedRandpd(D, K, P) 2 | %% Call randpd(D) K times and concatinate in pages 3 | % Add P to the diag of each matrix 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | if nargin < 3, P = 0; end 9 | 10 | S = zeros(D, D, K); 11 | for i=1:K 12 | S(:, :, i) = randpd(D) + diag(P*ones(D, 1)); 13 | end 14 | 15 | 16 | end 17 | -------------------------------------------------------------------------------- /util/findString.m: -------------------------------------------------------------------------------- 1 | function idx = findString(str, cellArray, ignoreCase) 2 | % Return a binary mask indicating where a string occurs in a cell array 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | if nargin < 3, ignoreCase = false; end 8 | if ignoreCase, fn = @(c)strcmpi(c,str); else fn = @(c)strcmp(c,str); end 9 | idx = cellfun(fn,cellArray); 10 | end 11 | -------------------------------------------------------------------------------- /util/removeFields.m: -------------------------------------------------------------------------------- 1 | function S = removeFields(S, varargin) 2 | %% Remove multiple fields from a structure without erroring if they don't exist 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | fields = varargin; 7 | for i=1:numel(fields) 8 | field = fields{i}; 9 | if isfield(S, field) 10 | S = rmfield(S, field); 11 | end 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /graph/pmtkGraphIsDag.m: -------------------------------------------------------------------------------- 1 | function b = pmtkGraphIsDag(adj_mat) 2 | % Returns true iff the graph has no directed cycles. 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | if bioinfoToolboxInstalled() 8 | b = graphisdag(sparse(adj_mat)); 9 | else 10 | adj_mat = double(adj_mat); 11 | R = reachability_graph(adj_mat); 12 | b = ~any(diag(R)==1); 13 | end 14 | -------------------------------------------------------------------------------- /metaTools/winpath.m: -------------------------------------------------------------------------------- 1 | function p = winpath() 2 | % Returns the current windows path in a cell array. 3 | % PMTKneedsMatlab 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | [err,wpath] = system('path'); % grab whole path string 8 | wpath = wpath(6:end); % first 5 chars are PATH= 9 | p = textscan(wpath,'%s','delimiter',';'); 10 | p = p{:}; 11 | 12 | end 13 | -------------------------------------------------------------------------------- /util/allSameTypes.m: -------------------------------------------------------------------------------- 1 | function tf = allSameTypes(cellArray) 2 | % Return true if all of the objects in the cellArray are of the same class 3 | % i.e. all doubles or all MvnDist() objects etc - false otherwise. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | c = class(cellArray{1}); 8 | tf = cellfun(@(x)isequal(class(x),c),cellArray); 9 | tf = all(tf(:)); 10 | end 11 | -------------------------------------------------------------------------------- /util/intersectPMTK.m: -------------------------------------------------------------------------------- 1 | function [C] = intersectPMTK(A, B) 2 | % Intersect two sets of positive integers faster than the built-in intersect 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | if isempty(A) || isempty(B) 8 | C = []; 9 | else 10 | bits = false(max(max(A), max(B)), 1); 11 | bits(A) = true; 12 | C = B(bits(B)); 13 | end 14 | 15 | end 16 | -------------------------------------------------------------------------------- /metaTools/dirs.m: -------------------------------------------------------------------------------- 1 | function d = dirs(p) 2 | % Return list of the directories in the specified directory. 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | if nargin == 0, p = pwd(); end 8 | 9 | dinfo = dir(p); 10 | names = {dinfo.name}; 11 | isdir = cell2mat({dinfo.isdir}) & cellfun(@(str)~startswith(str, '.'), names); 12 | d = names(isdir)'; 13 | 14 | 15 | end 16 | -------------------------------------------------------------------------------- /util/removeExtraSpaces.m: -------------------------------------------------------------------------------- 1 | function str = removeExtraSpaces(str) 2 | % Replace all contiguous sequences of spaces with a single space 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | if isempty(str); return; end 7 | prev = str; 8 | str = strrep(str, ' ', ' '); 9 | while ~strcmp(str, prev) 10 | prev = str; 11 | str = strrep(str, ' ', ' '); 12 | end 13 | 14 | end 15 | -------------------------------------------------------------------------------- /metaTools/visdiffOpen.m: -------------------------------------------------------------------------------- 1 | function visdiffOpen() 2 | %% Open Matlab's file comparison tool comparing the first two open docs 3 | % PMTKneedsMatlab 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | files = currentlyOpenFiles(); 9 | if numel(files) < 2 10 | fprintf('too few documents open\n'); 11 | return 12 | end 13 | visdiff(files{1}, files{2}); 14 | 15 | end 16 | -------------------------------------------------------------------------------- /graphics/shade.m: -------------------------------------------------------------------------------- 1 | 2 | % This file is from matlabtools.googlecode.com 3 | 4 | function shade(func,lower,left,right,color,resolution) 5 | if(nargin < 6) 6 | resolution = 0.0001; 7 | end 8 | hold on; 9 | res = left:resolution:right; 10 | x = repmat(res,2,1); 11 | y = [lower*ones(1,length(res)) ; rowvec(func(res))]; 12 | line(x,y,'Color',color); 13 | 14 | end 15 | -------------------------------------------------------------------------------- /stats/nchoosekln.m: -------------------------------------------------------------------------------- 1 | function nk = nchoosekln(n, k) 2 | % p(i) = ln nchoosek(n(i), k(i)) 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | % n! = gamma(n+1) 8 | nk = gammaln(n + 1) - gammaln(k + 1) - gammaln(n - k + 1); 9 | 10 | if 0 % debug 11 | for i=1:length(n) 12 | nk2(i) = log(nchoosek(n(i), k(i))); 13 | end 14 | assert(approxeq(nk, nk2)) 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /util/horzStackPages.m: -------------------------------------------------------------------------------- 1 | function A = horzStackPages(A) 2 | %% Horizontally stack matrix pages 3 | % The result is equivalent to [A(:, :, 1), A(:, :, 2), ... ,A(:, :, K)] 4 | % If A is transformed from size [N D K] to [N D*K] 5 | % (See also vertStackPages) 6 | % 7 | %% 8 | 9 | % This file is from matlabtools.googlecode.com 10 | 11 | [N, D, K] = size(A); 12 | A = reshape(A(:), [N, D*K]); 13 | end 14 | -------------------------------------------------------------------------------- /util/vertStackPages.m: -------------------------------------------------------------------------------- 1 | function A = vertStackPages(A) 2 | %% Vertically stack matrix pages 3 | % The result is equivalent to [A(:, :, 1); A(:, :, 2); ... ;A(:, :, K)] 4 | % If A is transformed from size [N D K] to [N*K D] 5 | % 6 | % 7 | %% 8 | 9 | % This file is from matlabtools.googlecode.com 10 | 11 | [N, D, K] = size(A); 12 | 13 | A = reshape(colvec(permute(A, [1 3 2])), [N*K, D]); 14 | end 15 | -------------------------------------------------------------------------------- /graphics/vectorToImage.m: -------------------------------------------------------------------------------- 1 | function img = vectorToImage(I, map) 2 | %% Inverse transformation for imageToVector() 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | sz = [map.M, map.N, map.d]; 8 | img = reshape(map.m2(I), sz); 9 | img(:, :, 3) = img(:, :, 3) - 2*map.nstates1; 10 | img(:, :, 2) = img(:, :, 2) - map.nstates1; 11 | img = reshape(map.m1(img(:)), sz); 12 | 13 | 14 | 15 | end 16 | -------------------------------------------------------------------------------- /util/argmax.m: -------------------------------------------------------------------------------- 1 | function indices = argmax(v) 2 | % Return the index vector of the largest element in the multidim array v 3 | % 4 | % Returns the first maximum in the case of ties. 5 | % Example: 6 | % X = [2 8 4; 7 3 9]; 7 | % argmax(X) = [2 3], i.e., row 2 column 3 8 | 9 | % This file is from matlabtools.googlecode.com 10 | 11 | 12 | [m i] = max(v(:)); 13 | indices = ind2subv(sizePMTK(v), i); 14 | 15 | end 16 | -------------------------------------------------------------------------------- /util/seteq.m: -------------------------------------------------------------------------------- 1 | function eq = seteq(varargin) 2 | % seteq(s1, s2, s3, ...) Returns true if s1=s2=s3 3 | % The elements of s{i} are sorted first. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | S1 = rowvec(sort(varargin{1})); 9 | eq = true; 10 | for i=2:nargin 11 | Si = varargin{i}; 12 | eq = eq && isequal(S1, rowvec(sort(Si))); 13 | if ~eq, return; end 14 | end 15 | end 16 | 17 | -------------------------------------------------------------------------------- /graphics/nsubplots.m: -------------------------------------------------------------------------------- 1 | function [ynum, xnum] = nsubplots(n) 2 | % Figure out how many plots in the y and x directions to cover n in total 3 | % while keeping the aspect ratio close to rectangular 4 | % but not too stretched 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | 9 | if n==2 10 | ynum = 2; xnum = 2; 11 | else 12 | xnum = ceil(sqrt(n)); 13 | ynum = ceil(n/xnum); 14 | end 15 | 16 | end 17 | -------------------------------------------------------------------------------- /metaTools/currentlyOpenFiles.m: -------------------------------------------------------------------------------- 1 | function files = currentlyOpenFiles() 2 | % Return a cell array of currently open files 3 | % PMTKneedsMatlab 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | E = com.mathworks.mlservices.MLEditorServices; 8 | jdocs = E.builtinGetOpenDocumentNames(); 9 | ndocs = numel(jdocs); 10 | files = cell(ndocs, 1); 11 | for i=1:ndocs 12 | files{i} = char(jdocs(i)); 13 | end 14 | -------------------------------------------------------------------------------- /util/assertTrue.m: -------------------------------------------------------------------------------- 1 | function assertTrue(predicate, message, varargin) 2 | % Test a predicate and throw an error, as the caller, if false 3 | % Supports sprintf type inputs. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | if nargin < 2, message = 'assertion error'; end 8 | if ~predicate, 9 | throwAsCaller(MException('AssertTrue:Failure', sprintf(message, varargin{:}))); 10 | end 11 | 12 | end 13 | -------------------------------------------------------------------------------- /util/insertBlankCells.m: -------------------------------------------------------------------------------- 1 | function CC = insertBlankCells(C, ndx) 2 | %% Insert blank rows of cells into a cell array at indices ndx 3 | % Returns a column cell array 4 | %% 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | 9 | 10 | N = size(C, 1)+numel(ndx); 11 | CC = cell(N, size(C, 2)); 12 | 13 | dndx = setdiffPMTK(1:N, ndx); 14 | CC(dndx, :) = C; 15 | 16 | 17 | 18 | 19 | 20 | 21 | end 22 | -------------------------------------------------------------------------------- /graph/isTopoOrdered.m: -------------------------------------------------------------------------------- 1 | function answer = isTopoOrdered(G) 2 | %% Return true iff the directed graph G is topologically ordered 3 | % that is j < k iff node j is not a child of node k. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | answer = false; 8 | nnodes = size(G, 1); 9 | for i=2:nnodes 10 | if any(children(G, i) <= i); 11 | return; 12 | end 13 | end 14 | answer = true; 15 | end 16 | -------------------------------------------------------------------------------- /util/partitionCell.m: -------------------------------------------------------------------------------- 1 | function [T, F, ndx] = partitionCell(C, fn) 2 | % Partition a cell into two according to a binary function 3 | % Partition the cell array C into those elements c for fn(c) returns true, 4 | % and those for which it returns false, (in that order). 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | 9 | ndx = cellfun(fn, C); 10 | T = C(ndx); 11 | F = C(~ndx); 12 | 13 | 14 | end 15 | -------------------------------------------------------------------------------- /stats/standardizeCols.m: -------------------------------------------------------------------------------- 1 | function [X, mu, s] = standardizeCols(X, mu, s) 2 | % Make each column of X be zero mean and unit variance 3 | % ie., var(X(:,j))=1 4 | % If mu and s are omitted, it computed from X and returned for use at test time 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | 9 | if nargin < 2, mu = []; s = []; end 10 | [X,mu] = centerCols(X,mu); 11 | [X,s] = mkUnitVariance(X,s); 12 | 13 | end 14 | -------------------------------------------------------------------------------- /stats/splineBasis.m: -------------------------------------------------------------------------------- 1 | function [X, knots] = splineBasis(x, K, knots) 2 | %% Spline basis function expansion 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | if nargin < 2, K = 100; end 8 | if nargin < 3, knots = linspace(min(x), max(x), K); end 9 | K = length(knots); 10 | d = length(knots); 11 | [junk, bind] = histc(x,knots); 12 | n = length(x); 13 | X = sparse((1:n)',bind,1,n,d); % design matrix 14 | 15 | 16 | end 17 | -------------------------------------------------------------------------------- /util/catStruct.m: -------------------------------------------------------------------------------- 1 | function s = catStruct(s1,s2) 2 | % Combine two structs into one with the fields and values from both 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | if(numel(intersect(fieldnames(s1),fieldnames(s2)))>0) 7 | error('Names are not unique'); 8 | end 9 | 10 | s = s1; 11 | newnames = fieldnames(s2); 12 | for i=1:numel(newnames) 13 | s.(newnames{i}) = s2.(newnames{i}); 14 | end 15 | 16 | 17 | end 18 | -------------------------------------------------------------------------------- /util/cellfind.m: -------------------------------------------------------------------------------- 1 | function ndx = cellfind(cellarray, value, varargin) 2 | % A find function for cell arrays 3 | % 4 | % example 5 | % 6 | % a = {[], 1, 1:2, 1:3, 1:4, 1:5, 1:6, 1:7, 1:8} 7 | % cellfind(a, 1:3) 8 | % ans = 4 9 | 10 | % This file is from matlabtools.googlecode.com 11 | 12 | if iscell(value) && ~iscell(cellarray{1}), value = value{:}; end 13 | ndx = find(cellfun(@(x)isequal(x, value), cellarray), varargin{:}); 14 | end 15 | -------------------------------------------------------------------------------- /util/padOnes.m: -------------------------------------------------------------------------------- 1 | function A = padOnes(data, ndx, sz) 2 | % Pad a vector or matrix with ones 3 | % Returns a vector or matrix with dimensions sz, with ones everywhere 4 | % except at linear indices ndx, where the corresponding entry from data 5 | % is put. 6 | 7 | % This file is from matlabtools.googlecode.com 8 | 9 | if isscalar(sz) 10 | sz = [sz, 1]; 11 | end 12 | A = ones(sz); 13 | A(ndx) = colvec(data); 14 | end 15 | -------------------------------------------------------------------------------- /metaTools/formatHtmlText.m: -------------------------------------------------------------------------------- 1 | function S = formatHtmlText(txt, varargin) 2 | %% Format multiline text for inclusion in an html report 3 | % This is like sprintf, but txt is a cell array. Each entry in the array 4 | % is treated as a separate line with html
breaks added to the end of 5 | % each. 6 | % 7 | % 8 | %% 9 | 10 | % This file is from matlabtools.googlecode.com 11 | 12 | S = sprintf(catString(txt, '
\n'), varargin{:}); 13 | end 14 | -------------------------------------------------------------------------------- /util/padZeros.m: -------------------------------------------------------------------------------- 1 | function A = padZeros(data, ndx, sz) 2 | % Pad a vector or matrix with zeros 3 | % Returns a vector or matrix with dimensions sz, with zeros everywhere 4 | % except at linear indices ndx, where the corresponding entry from data 5 | % is put. 6 | 7 | % This file is from matlabtools.googlecode.com 8 | 9 | if isscalar(sz) 10 | sz = [sz, 1]; 11 | end 12 | A = zeros(sz); 13 | A(ndx) = colvec(data); 14 | end 15 | -------------------------------------------------------------------------------- /metaTools/removeShadows.m: -------------------------------------------------------------------------------- 1 | function removeShadows(quiet) 2 | % Remove the shadows created by shadowFunction() 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | SetDefaultValue(1, 'quiet', false); 7 | delete(fullfile(tempdir(), 'matlabShadow', '*.m')); 8 | removePath(fullfile(tempdir(), 'matlabShadow')); 9 | warning('on', 'MATLAB:dispatcher:nameConflict'); 10 | if ~quiet 11 | fprintf('all shadows removed\n'); 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /oop/isclassdef.m: -------------------------------------------------------------------------------- 1 | function bool = isclassdef(classname) 2 | % Test if a class by the specified name exists on the Matlab path 3 | % PMTKneedsMatlab 2008 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | if iscellstr(classname) 8 | bool = cellfun(@isclassdef,classname); 9 | return; 10 | end 11 | if exist(classname,'file') ~= 2; 12 | bool = false; return; 13 | end 14 | bool = ~isempty(meta.class.fromName(classname)); 15 | end 16 | -------------------------------------------------------------------------------- /stats/satDataLoad.m: -------------------------------------------------------------------------------- 1 | function [X,y] = satDataLoad() 2 | 3 | %stat = load('stat2.dat'); % Johnson and Albert p77 table 3.1 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | stat = loadData('sat'); % Johnson and Albert p77 table 3.1 8 | % stat=[pass(0/1), 1, 1, sat_score, grade in prereq] 9 | % where the grade in prereq is encoded as A=5,B=4,C=3,D=2,F=1 10 | y = stat(:,1); 11 | N = length(y); 12 | X = [ones(N,1) stat(:,4)]; 13 | 14 | end 15 | -------------------------------------------------------------------------------- /util/google.m: -------------------------------------------------------------------------------- 1 | function google(varargin) 2 | % Open google in your default browser and search for the specified query 3 | % 4 | % 5 | % Example: 6 | % 7 | % google matlab interface to graphViz 8 | % PMTKneedsMatlab 9 | %% 10 | 11 | % This file is from matlabtools.googlecode.com 12 | 13 | query = catString(varargin, ' '); 14 | web('-browser', sprintf('http://www.google.ca/search?hl=en&source=hp&q=%s&btnG=Google+Search&meta=&aq=f&oq=', query)); 15 | end 16 | -------------------------------------------------------------------------------- /metaTools/findIdenticalShadowedCopies.m: -------------------------------------------------------------------------------- 1 | function f = findIdenticalShadowedCopies() 2 | % Searches through every m-file and finds exact duplicates 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | m = mfiles(pmtk3Root()); 7 | f = {}; 8 | for i=1:numel(m) 9 | w = which('-all',m{i}); 10 | if(numel(w) == 2 && isequal(getText(w{1}),getText(w{2}))) 11 | f = [f, w{2}]; %#ok 12 | end 13 | 14 | end 15 | f = f'; 16 | 17 | end 18 | -------------------------------------------------------------------------------- /stats/nanmeanPMTK.m: -------------------------------------------------------------------------------- 1 | function m = nanmeanPMTK(X, dim) 2 | % Replacement for the stats toolbox nanmean function 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | if nargin == 1 8 | dim = find(size(X)~=1, 1); 9 | if isempty(dim), dim = 1; end 10 | end 11 | 12 | nans = isnan(X); 13 | X(nans(:)) = 0; 14 | n = size(X, dim) - sum(nans, dim); 15 | if ~any(n) 16 | m = NaN; 17 | else 18 | m = sum(X, dim)./n; 19 | end 20 | 21 | end 22 | -------------------------------------------------------------------------------- /stats/deflation.m: -------------------------------------------------------------------------------- 1 | function [V,lambda] = deflation(C, K) 2 | % Compute largest K eigenvectors and eigenvalues of symmetric matrix 3 | % using power method combined with successive deflation 4 | % Based on code by Mark Girolami 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | 9 | d = length(C); 10 | V = zeros(d,K); 11 | for j=1:K 12 | [lambda(j), V(:,j)] = powerMethod(C); 13 | C = C - lambda(j)*V(:,j)*V(:,j)'; % deflation 14 | end 15 | 16 | end 17 | -------------------------------------------------------------------------------- /metaTools/providePath.m: -------------------------------------------------------------------------------- 1 | function providePath(p) 2 | % Like builtin addpath function, but checks if p is already on the path 3 | % and does nothing if it is, (rather than issue a warning as addpath does). 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | if ischar(p) 9 | p = tokenize(p, ';'); 10 | end 11 | for i=1:numel(p) 12 | if ~onMatlabPath(p{i}) 13 | addpath(p{i}) 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /stats/fisheririsLoad.m: -------------------------------------------------------------------------------- 1 | 2 | % This file is from matlabtools.googlecode.com 3 | 4 | function [X,y,classnames,varnames] = fisheririsLoad() 5 | 6 | loadData('fisherIrisData') % meas 150x4, species 150x1 cell array 7 | X = meas; 8 | classnames = {'setosa', 'versicolor', 'virginica'}; 9 | varnames = {'sepal length', 'sepal width', 'petal length', 'petal width'}; 10 | y = zeros(1,150); 11 | for c=1:3 12 | ndx = strmatch(classnames{c},species); 13 | y(ndx) = c; 14 | end 15 | -------------------------------------------------------------------------------- /stats/mkUnitNorm.m: -------------------------------------------------------------------------------- 1 | function [X, s] = mkUnitNorm(X, s) 2 | % Make each column of X be norm 1 3 | % ie., sum_i x(i,j)^2 = 1 (so var(X(:,j),1)=1/n) 4 | % If s is omitted, it is computed from X and returned for use at test time 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | 9 | if nargin < 2, s = []; end 10 | [n p] = size(X); 11 | if isempty(s) 12 | s = sqrt(sum(X.^2)); 13 | end 14 | %X = X./repmat(s, n, 1); 15 | X = bsxfun(@rdivide,X,s); 16 | 17 | end 18 | -------------------------------------------------------------------------------- /graph/ancestors.m: -------------------------------------------------------------------------------- 1 | function a = ancestors(adj_mat,i) 2 | % Recursively find all ancestors of a a node, (parents, grandparents, ... etc) 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | a = []; 8 | if isempty(parents(adj_mat,i)) 9 | return; 10 | else 11 | p = parents(adj_mat,i); 12 | for i=1:numel(p) 13 | a = [a,ancestors(adj_mat,p(i))]; 14 | end 15 | a = [p,a]; 16 | end 17 | 18 | 19 | 20 | 21 | end 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /graphics/rel2absX.m: -------------------------------------------------------------------------------- 1 | function xabs = rel2absX(xpos, ax) 2 | % Convert from axis-relative coordinates to absolute coordinates within the 3 | % figure. See also rel2absY. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | if nargin < 2, 8 | ax = gca; 9 | end 10 | xlim = get(ax,'xlim'); 11 | xmin = xlim(1); 12 | xmax = xlim(2); 13 | xscale = xmax - xmin; 14 | axAbs = get(ax,'Position'); 15 | xabs = axAbs(1) + ((xpos-xmin) ./ xscale).*axAbs(3); 16 | end 17 | 18 | -------------------------------------------------------------------------------- /oop/localMethods.m: -------------------------------------------------------------------------------- 1 | function local = localMethods(classname,allowAbstract) 2 | % Return the local methods of a class 3 | % - see islocal() for a description of what 'local' means. 4 | % PMTKneedsMatlab 2008 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | if nargin < 2, allowAbstract = false; end 9 | m = methods(classname); if isempty(m), local = {}; return; end 10 | local = filterCell(methods(classname),@(m)islocal(m,classname,allowAbstract)); 11 | 12 | end 13 | -------------------------------------------------------------------------------- /graphics/colorbars.m: -------------------------------------------------------------------------------- 1 | function colorbars(barGraphHandle,indices,color) 2 | % set elements of a bar graph to specified color 3 | % eg x = -2.9:0.2:2.9; h = bar(x,exp(-x.*x)); colorbars(h,10:15,'r') 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | child = get(barGraphHandle, 'Children'); 9 | xdata = get(child, 'XData'); 10 | ydata = get(child, 'YData'); 11 | changeX = xdata(:,indices); 12 | changeY = ydata(:,indices); 13 | patch(changeX,changeY,color); 14 | end 15 | -------------------------------------------------------------------------------- /util/argmin.m: -------------------------------------------------------------------------------- 1 | function indices = argmin(v) 2 | % Return the index vector of the smallest element in the multidim array v 3 | % 4 | % Returns the first minimum in the case of ties. 5 | % Example: 6 | % X = [2 8 4; 7 3 9]; 7 | % argmin(X) = [1 1], i.e., row 1 column 1 8 | 9 | % This file is from matlabtools.googlecode.com 10 | 11 | 12 | [m i] = min(v(:)); %#ok 13 | if isvector(v) 14 | indices = i; 15 | else 16 | indices = ind2subv(sizePMTK(v), i); 17 | end 18 | 19 | end 20 | -------------------------------------------------------------------------------- /graphics/plotColors.m: -------------------------------------------------------------------------------- 1 | 2 | % This file is from matlabtools.googlecode.com 3 | 4 | function [styles, colors, symbols, str] = plotColors() 5 | 6 | colors = ['b' 'r' 'k' 'g' 'c' 'y' 'm' ... 7 | 'r' 'b' 'k' 'g' 'c' 'y' 'm']; 8 | symbols = ['o' 'x' '*' '>' '<' '^' 'v' ... 9 | '+' 'p' 'h' 's' 'd' 'o' 'x']; 10 | styles = {'-', ':', '-.', '--', '-', ':', '-.', '--'}; 11 | 12 | for i=1:length(colors) 13 | str{i} = sprintf('-%s%s', colors(i), symbols(i)); 14 | end 15 | 16 | end 17 | -------------------------------------------------------------------------------- /util/addToStruct.m: -------------------------------------------------------------------------------- 1 | function S = addToStruct(S, varargin) 2 | %% Add variables to a struct using their names in the current scope 3 | % See also structure.m 4 | % 5 | % Caution - this will overwrite any existing fields by the input names. 6 | % *** does not support anonymous variables as in addToStruct(S, 25, 2+3), etc *** 7 | % 8 | %% 9 | 10 | % This file is from matlabtools.googlecode.com 11 | 12 | for i=2:nargin 13 | S.(inputname(i)) = varargin{i-1}; 14 | end 15 | end 16 | 17 | -------------------------------------------------------------------------------- /util/removeNonPrintedChars.m: -------------------------------------------------------------------------------- 1 | function text = removeNonPrintedChars(text) 2 | %% Remove all non-printing characters, (except regular blank space) 3 | % and replace them with blanks. Remove superfluous blanks. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | if iscell(text) 9 | text = cellfuncell(@removeNonPrintedChars, text); 10 | return 11 | end 12 | 13 | text(~isstrprop(text, 'print') ) = ' '; 14 | text = removeExtraSpaces(text); 15 | end 16 | 17 | 18 | -------------------------------------------------------------------------------- /metaTools/missingEnds.m: -------------------------------------------------------------------------------- 1 | function R = missingEnds() 2 | % Find all non-builtin matlab files missing a final "end" statement 3 | % 4 | % Return a list of all of the non-builtin mfiles on the matlab path that 5 | % are missing the syntactically optional end keyword at the end of the 6 | % function. 7 | 8 | % This file is from matlabtools.googlecode.com 9 | 10 | fileNames = allMfilesOnPath(); 11 | ndx = cellfun(@isEndKeywordMissing, fileNames); 12 | R = fileNames(ndx); 13 | end 14 | 15 | -------------------------------------------------------------------------------- /stats/logdet.m: -------------------------------------------------------------------------------- 1 | function y = logdet(A) 2 | % Compute log(det(A)) where A is positive-definite 3 | % This is faster and more stable than using log(det(A)). 4 | % 5 | %PMTKauthor Tom Minka 6 | % (c) Microsoft Corporation. All rights reserved. 7 | 8 | % This file is from matlabtools.googlecode.com 9 | 10 | try 11 | U = chol(A); 12 | y = 2*sum(log(diag(U))); 13 | catch %#ok 14 | y = 0; 15 | warning('logdet:posdef', 'Matrix is not positive definite'); 16 | end 17 | 18 | end 19 | -------------------------------------------------------------------------------- /graph/isWeaklyConnected.m: -------------------------------------------------------------------------------- 1 | function answer = isWeaklyConnected(G) 2 | %% Check if a directed graph is (at least) weakly connected 3 | % A directed graph is called weakly connected if replacing all of its 4 | % directed edges with undirected edges produces a connected (undirected) 5 | % graph. From http://en.wikipedia.org/wiki/Connectivity_(graph_theory) 6 | %% 7 | 8 | % This file is from matlabtools.googlecode.com 9 | 10 | answer = all(colvec(reachability_graph(mkSymmetric(G)))); 11 | end 12 | -------------------------------------------------------------------------------- /graph/ndags.m: -------------------------------------------------------------------------------- 1 | function ND = ndags(N) 2 | % Computes number of dags on N nodes using Robinson's 1973 recursion 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | %PMTKauthor Robert Tseng, Simon Suyadi 8 | 9 | 10 | numdags = zeros(1,N+1); 11 | numdags(1) = 1; 12 | for i = 2:N+1 13 | numdags(i) = 0; 14 | for k = 1:i-1 15 | numdags(i) = numdags(i) + (-1)^(k-1) * nchoosek(i-1, k) * ... 16 | 2^(k*(i-1-k)) * numdags(i-k); 17 | end 18 | end 19 | ND = numdags(N+1); 20 | -------------------------------------------------------------------------------- /stats/mkUnitVariance.m: -------------------------------------------------------------------------------- 1 | function [X, s] = mkUnitVariance(X, s) 2 | % Make each column of X be variance 1 3 | % ie., sum_i x(i,j)^2 = n (so var(X(:,j))=1) 4 | % If s is omitted, it computed from X and returned for use at test time 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | 9 | if nargin < 2, s = []; end 10 | if isempty(s) 11 | s = std(X); 12 | s((s0); 12 | else 13 | % This computes C = G + G^2 + ... + G^{n-1} 14 | n = length(G); 15 | A = G; 16 | C = zeros(n); 17 | for i=1:n-1 18 | C = C + A; 19 | A = A * G; 20 | end 21 | C = (C > 0); 22 | end 23 | 24 | end 25 | -------------------------------------------------------------------------------- /meta/insertCopyrightMatlabTools.m: -------------------------------------------------------------------------------- 1 | function insertCopyrightMatlabTools(fname) 2 | %% Insert a copyright notice into every matlabTools .m file 3 | % or into just the specified file. 4 | %% 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | text = 'This file is from matlabtools.googlecode.com'; 9 | 10 | if nargin > 0 11 | insertCopyright(text, fname); 12 | else 13 | flist = filelist(matlabToolsRoot(), '*.m', true); 14 | for i=1:numel(flist) 15 | fprintf('inserting into %s\n', flist{i}); 16 | insertCopyright(text, flist{i}); 17 | end 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /meta/localReports/matlabToolsSynopses.m: -------------------------------------------------------------------------------- 1 | function matlabToolsSynopses() 2 | %% Generate the synopses listing files and one line desriptions for matlabTools 3 | % PMTKneedsMatlab 4 | %% 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | dest = fullfile(matlabToolsRoot(), 'docs', 'synopsis'); 9 | d = {'graph', 'graphics', 'metaTools', 'oop', 'stats', 'util'}; 10 | for i=1:numel(d) 11 | directory = fullfile(matlabToolsRoot(), d{i}); 12 | outputFile = fullfile(dest, sprintf('%s.html', d{i})); 13 | generateSynopsisTable(directory, outputFile, matlabToolsRoot()); 14 | end 15 | %% 16 | end 17 | -------------------------------------------------------------------------------- /util/collapseCell.m: -------------------------------------------------------------------------------- 1 | function v = collapseCell(c) 2 | % Collapse a nested cell array as much as possible 3 | % 4 | % Example: 5 | % collapseCell({1,2,3,{4,5,6,{7,8,9,{10,11,12}}},13,14,{15,16,{17,18,19}}})' 6 | %ans = 7 | % 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 8 | 9 | % This file is from matlabtools.googlecode.com 10 | 11 | 12 | if ~iscell(c),v = c; return; end 13 | if cellDepth(c) < 2 14 | v = colvec(cell2mat(cellfuncell(@colvec,c))); 15 | else 16 | v = cellValues(colvec(cellfuncell(@cellValues,c))); 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /stats/powerMethod.m: -------------------------------------------------------------------------------- 1 | function [lam, u, iter] = powerMethod(C) 2 | % Power method for finding the leading eigenvalue/ vector of a pd matrix 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | maxIter = 100; 8 | tol = 1e-10; 9 | converged = 0; 10 | 11 | n = length(C); 12 | u = randn(n,1); u = u / norm(u); 13 | iter = 1; 14 | while ~converged & (iter < maxIter) 15 | oldu = u; 16 | u = C*u; 17 | u = u / norm(u); 18 | lam = u'*C*u; 19 | converged = (norm(u - oldu) < tol); 20 | iter = iter + 1; 21 | end 22 | if iter > maxIter 23 | warning('did not converge') 24 | end 25 | 26 | end 27 | -------------------------------------------------------------------------------- /metaTools/onMatlabPath.m: -------------------------------------------------------------------------------- 1 | function answer = onMatlabPath(p, loose) 2 | % Return true if the specified path is currently on the Matlab search path. 3 | % If loose is true, (default = false), then answer is true if any 4 | % subdirectory of p is on the path. 5 | % 6 | %% Example: 7 | % 8 | % onMatlabPath 'C:\pmtkData' 9 | %% 10 | 11 | % This file is from matlabtools.googlecode.com 12 | 13 | SetDefaultValue(2, 'loose', false); 14 | if loose 15 | answer = any(cellfun(@(s)isSubstring(p, s), tokenize(path(), ';'))); 16 | else 17 | answer = any(cellfun(@(s)strcmpi(s, p), tokenize(path(), ';'))); 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /stats/rescaleData.m: -------------------------------------------------------------------------------- 1 | function [y, minx, rangex] = rescaleData(x, minVal, maxVal, minx, rangex) 2 | % Rescale columns to lie in the range minVal:maxVal (defaults to -1:1) 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | x = double(x); 8 | [n d] = size(x); 9 | if nargin < 2 10 | minVal = -1; maxVal = 1; 11 | end 12 | if nargin < 4 || isempty(minx) 13 | minx = min(x,[],1); rangex = drange(x,1); 14 | end 15 | % rescale to 0:1 16 | y = (x-repmat(minx,n,1)) ./ repmat(rangex, n, 1); 17 | % rescale to 0:(max-min) 18 | y = y * (maxVal-minVal); 19 | % shift to min:max 20 | y = y + minVal; 21 | 22 | end 23 | -------------------------------------------------------------------------------- /meta/changeCopyrightMatlabTools.m: -------------------------------------------------------------------------------- 1 | function changeCopyrightMatlabTools(oldStr, newStr, fname) 2 | %% Modify the copyright line in every matlabTools file 3 | % or in just the specified file. The oldStr should be exactly as it appears 4 | % in the file(s), including case, spaces, and leading '%' chars. 5 | %% 6 | 7 | % This file is from matlabtools.googlecode.com 8 | 9 | if nargin > 2 10 | searchAndReplaceLine(fname, oldStr, newStr); 11 | else 12 | flist = filelist(matlabToolsRoot(), '*.m', true); 13 | for i=1:numel(flist) 14 | searchAndReplaceLine(flist{i}, oldStr, newStr); 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /stats/dblquadrep.m: -------------------------------------------------------------------------------- 1 | function val = dblquadrep(f, range) 2 | % Like dblquad, except we replicate x2 to be same size as x1 3 | % before calling f([x1(i) x2(i)]) 4 | % Thus for dblquadrep, f should handle an n*2 matrix of inputs 5 | % whereas for dblquad, f should handle an n*1 vector and a scalar 6 | 7 | % This file is from matlabtools.googlecode.com 8 | 9 | foo = @(x1,x2) f(replicateX2(x1,x2)); 10 | val = dblquad(foo, range(1), range(2), range(3), range(4)); 11 | end 12 | 13 | function X = replicateX2(x1, x2) 14 | % X(i,:) = [x1(i) x2] 15 | n = length(x1); 16 | x2 = x2*ones(n,1); 17 | X = [x1(:) x2(:)]; 18 | end 19 | 20 | 21 | -------------------------------------------------------------------------------- /util/insertSingleton.m: -------------------------------------------------------------------------------- 1 | function A = insertSingleton(A, d) 2 | %% Insert a singleton dimension at dimension d. 3 | % This does not change the *linear* indices of the elements of A. 4 | % 5 | % Example: 6 | % 7 | % A = rand(3, 5, 2, 4); 8 | % size(A) 9 | % ans = 10 | % 3 5 2 4 11 | % 12 | % As = insertSingleton(A, 3); 13 | % size(As) 14 | % ans = 15 | % 3 5 1 2 4 16 | % 17 | % assert(isequal(A(:), As(:))); 18 | % 19 | %% 20 | 21 | % This file is from matlabtools.googlecode.com 22 | 23 | nd = ndims(A); 24 | perm = [1:d-1, nd+1, d:nd]; 25 | A = permute(A, perm); 26 | 27 | end 28 | -------------------------------------------------------------------------------- /util/setdiffPMTK.m: -------------------------------------------------------------------------------- 1 | function C = setdiffPMTK(A,B) 2 | % Efficiently calculate the set difference of two sets of positive integers 3 | % (much faster than built-in setdiff) 4 | % C = setdiffPMTK(A,B) 5 | % C = A \ B = { things in A that are not in B } 6 | % 7 | % Original by Kevin Murphy, modified by Leon Peshkin 8 | 9 | % This file is from matlabtools.googlecode.com 10 | 11 | 12 | if isempty(A) 13 | C = []; 14 | elseif isempty(B) 15 | C = A; 16 | else % both non-empty 17 | bits = false(1, max(max(A), max(B))); 18 | bits(A) = true; 19 | bits(B) = false; 20 | C = A((bits(A))); 21 | end 22 | 23 | end 24 | -------------------------------------------------------------------------------- /util/setSeed.m: -------------------------------------------------------------------------------- 1 | function setSeed(seed) 2 | % Set the random seed 3 | % We don't use the new RandStream class for compatibility with Octave and 4 | % older versions of Matlab. In the future it may be necessary to test the 5 | % Matlab version and call the appropriate code. 6 | 7 | % This file is from matlabtools.googlecode.com 8 | 9 | global RNDN_STATE RND_STATE 10 | if nargin == 0 11 | seed = 0; 12 | end 13 | warning('off', 'MATLAB:RandStream:ReadingInactiveLegacyGeneratorState'); 14 | RNDN_STATE = randn('state'); %#ok<*RAND> 15 | randn('state', seed); 16 | RND_STATE = rand('state'); 17 | rand('twister', seed); 18 | end 19 | -------------------------------------------------------------------------------- /util/ndimsPMTK.m: -------------------------------------------------------------------------------- 1 | function d = ndimsPMTK(M) 2 | % Like the built-in ndims, except handles [] and vectors properly 3 | % 4 | % The behavior is best explained by examples 5 | % - M = [], ndimsPMTK(M) = 0, ndims(M) = 2 6 | % - M = rand(1,1), ndimsPMTK(M) = 1, ndims(M) = 2 7 | % - M = rand(2,1), ndimsPMTK(M) = 1, ndims(M) = 2 8 | % - M = rand(1,2,1), ndimsPMTK(M) = 2, ndims(M) = 2 9 | % - M = rand(1,2,2), ndimsPMTK(M) = 3, ndims(M) = 3 10 | 11 | % This file is from matlabtools.googlecode.com 12 | 13 | 14 | if isempty(M) 15 | d = 0; 16 | elseif isvector(M) 17 | d = 1; 18 | else 19 | d = ndims(M); 20 | end 21 | -------------------------------------------------------------------------------- /stats/randsplit.m: -------------------------------------------------------------------------------- 1 | function Xsplit = randsplit(X, k) 2 | % Split rows of X into k (roughly) equal random partitions 3 | % Xsplit is a k-by-1 cell array. The last cell will have 4 | % n - (k-1)*floor(n/k) elements, all others will have floor(n/k). 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | 9 | n = size(X, 1); 10 | Xsplit = cell(k, 1); 11 | perm = randperm(n); 12 | psize = floor(n/k); 13 | for i=1:k 14 | start = psize*(i-1)+1; 15 | ndx = start:start+psize-1; 16 | Xsplit{i} = X(perm(ndx), :); 17 | end 18 | if psize*k < n 19 | Xsplit{end} = [Xsplit{end}; X(perm(psize*k+1:end), :)]; 20 | end 21 | 22 | end 23 | -------------------------------------------------------------------------------- /graph/moralizeGraph.m: -------------------------------------------------------------------------------- 1 | function [M, moral_edges] = moralizeGraph(G) 2 | % Ensure that for every child, all its parents are married (connected) 3 | % and then drop directionality of edges. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | M = G; 9 | n = length(M); 10 | for i=1:n 11 | fam = family(G, i); 12 | M(fam, fam)=1; 13 | end 14 | M = setdiag(M, 0); 15 | if nargout > 1 16 | moral_edges = sparse(triu(max(0, M-G), 1)); 17 | end 18 | M = mkSymmetric(M); 19 | end 20 | 21 | function ps = parents(G, i) 22 | ps = find(G(:, i))'; 23 | end 24 | 25 | function f = family(G, i) 26 | f = [parents(G, i) i]; 27 | end 28 | 29 | -------------------------------------------------------------------------------- /metaTools/countLinesOfCodeDir.m: -------------------------------------------------------------------------------- 1 | function n = countLinesOfCodeDir(d, excludeComments, recursive, filemask) 2 | % Count the total lines of code in all functions in a directory structure 3 | % If recursive is true, (default) include subdirectories as well. 4 | % 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | 9 | if nargin < 2, excludeComments = true; end 10 | if nargin < 3, recursive = true; end 11 | if nargin < 4, filemask = {'*.m', '*.c', '*.cpp', '*.h', '*.py'}; end 12 | 13 | f = filelist(d, filemask, recursive); 14 | counts = cellfun(@(c)countLinesOfCode(c, excludeComments), f); 15 | n = sum(counts); 16 | 17 | 18 | end 19 | -------------------------------------------------------------------------------- /stats/sumOver.m: -------------------------------------------------------------------------------- 1 | function T = sumOver(T, sum_over) 2 | % Sum multidimensional array T over dimensions 'dims' and squeeze the result 3 | % This is like the built-in sum, but you can pass a vector of dimensions to sum over 4 | % Example 5 | % T = reshape(1:8, [2 2 2]) 6 | % sumOver(T, [1 3]) = sum(sum(T,1),3) = [14 22] = [1+2 + 5+6, 3+4 + 7+8] 7 | % since 8 | %T(:,:,1) = 9 | % 1 3 10 | % 2 4 11 | %T(:,:,2) = 12 | % 5 7 13 | % 6 8 14 | 15 | % This file is from matlabtools.googlecode.com 16 | 17 | 18 | for i=1:numel(sum_over) 19 | T = sum(T, sum_over(i)); 20 | end 21 | T = squeeze(T); 22 | 23 | 24 | 25 | end 26 | -------------------------------------------------------------------------------- /stats/mutualInfoClassFeaturesBinary.m: -------------------------------------------------------------------------------- 1 | function [mi] = mutualInfoClassFeaturesBinary(X,y) 2 | % Mutual information between binary features and class label 3 | % mi(j) = I(X(j), Y) 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | model = naiveBayesFit(X,y); 8 | py = model.classPrior; 9 | pxy = model.theta; % pxy(c,j) = p(xj=1|y=c) 10 | [C,D] = size(pxy); 11 | % px(j) = p(x=j) = sum_c p(xj=1|y=c) p(y=c) 12 | px = sum(repmat(py(:), 1, D) .* pxy, 1); 13 | mi = zeros(1,D); 14 | for c=1:C 15 | mi = mi + py(c) * pxy(c,:) .* log2(pxy(c,:) ./ (px)) + ... 16 | py(c) * (1-pxy(c,:)) .* log2( (1-pxy(c,:)) ./ ((1-px)) ); 17 | end 18 | 19 | end 20 | -------------------------------------------------------------------------------- /metaTools/showFigures.m: -------------------------------------------------------------------------------- 1 | function showFigures() 2 | % This function undoes the effect of hideFigures 3 | %- see it for details. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | 9 | set(0, 'defaultFigureVisible', 'on'); 10 | set(0, 'defaultAxesVisible', 'on'); 11 | fullpath = fullfile(tempdir, 'matlabFigShadow'); 12 | removePath(fullpath); 13 | if exist(fullfile(fullpath, 'figure.m'), 'file') 14 | delete(fullfile(fullpath, 'figure.m')); 15 | delete(fullfile(fullpath, 'axes.m')); 16 | rmdir(fullpath); 17 | end 18 | warning('on', 'MATLAB:dispatcher:nameConflict') 19 | fprintf('figures will now be displayed again\n'); 20 | 21 | 22 | end 23 | -------------------------------------------------------------------------------- /graphics/imageToVector.m: -------------------------------------------------------------------------------- 1 | function [I, map] = imageToVector(img) 2 | %% Convert an int valued [M, N, d] image matrix to a vector 3 | % preserving information. 4 | % Use vectorToImage to convert back 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | 9 | [M, N, d] = size(img); 10 | 11 | nstates0 = max(img(:)); 12 | [img, m1] = canonizeLabels(img); 13 | nstates1 = max(img(:)); 14 | img = reshape(img, [M, N, d]); 15 | img(:, :, 2) = img(:, :, 2) + nstates1; 16 | img(:, :, 3) = img(:, :, 3) + 2*nstates1; 17 | [img, m2] = canonizeLabels(img); 18 | I = img(:); 19 | map = structure(M, N, d, nstates0, nstates1, m1, m2); 20 | 21 | 22 | 23 | end 24 | 25 | 26 | -------------------------------------------------------------------------------- /stats/nanvarPMTK.m: -------------------------------------------------------------------------------- 1 | function v = nanvarPMTK(X, w, dim) 2 | % Replacement for the stats toolbox nanvar function 3 | % However, unlike nanvar, this does not support weighted variance. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | if nargin < 2 9 | w = 0; 10 | end 11 | 12 | if nargin < 3 13 | dim = find(size(X)~=1, 1, 'first'); 14 | if isempty(dim), 15 | dim = 1; 16 | end 17 | end 18 | 19 | n = sum(~isnan(X), dim); 20 | if w 21 | norm = max(n, 1); 22 | else 23 | norm = max(n-1, 1); 24 | end 25 | norm(n==0) = NaN; 26 | Xbar = bsxfun(@minus, X, nanmeanPMTK(X, dim)); 27 | v = nansumPMTK(abs(Xbar).^2, dim) ./ norm; 28 | end 29 | -------------------------------------------------------------------------------- /metaTools/htmFormatText.m: -------------------------------------------------------------------------------- 1 | function S = htmFormatText(varargin) 2 | %% Format a multiline comment for html 3 | % This is just like multiLineString except it adds html breaks
to the 4 | % end of each line. 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | stack = dbstack('-completenames'); 9 | if numel(stack) < 2 10 | error('This function cannot be called from the command prompt'); 11 | end 12 | T = getText(stack(2).file); 13 | T = T((stack(2).line):end); 14 | 15 | start = cellfind(T, '%{', 1, 'first'); 16 | endl = cellfind(T, '%}', 1, 'first'); 17 | T = strtrim(T(start+1:endl-1)); 18 | S = sprintf(catString(T, '
\n'), varargin{:}); 19 | 20 | end 21 | -------------------------------------------------------------------------------- /stats/partitionedSum.m: -------------------------------------------------------------------------------- 1 | function S = partitionedSum(X, y, C) 2 | % Group the rows of X according to the class labels in y and sum each group 3 | % 4 | % X - an n-by-d matrix of doubles 5 | % y - an n-by-1 vector of ints in 1:C 6 | % C - (optional) the number of classes, (calculated if not specified) 7 | % 8 | % M - a C-by-d matrix of sums. 9 | % 10 | % See also - partitionedMean 11 | 12 | % This file is from matlabtools.googlecode.com 13 | 14 | 15 | 16 | if nargin < 3 17 | C = nunique(y); 18 | end 19 | if isOctave 20 | S = bsxfun(@eq, (1:C).', y.')*X; 21 | else 22 | S = bsxfun(@eq, sparse(1:C).', y.')*X; 23 | end 24 | 25 | 26 | end 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /stats/preprocessorCreate.m: -------------------------------------------------------------------------------- 1 | function [pp] = preprocessorCreate(varargin) 2 | % Make a preprocessor structure 3 | % Options: 4 | % 5 | % standardizeX - if true, makes columsn of X zero mean and unit variance [true] 6 | % rescaleX - if true, scale columns of X to lie in [-1, +1] [false] 7 | % kernelFn - if not [], apply kernel fn to X default [] 8 | % poly - if not [], specify degree of polynomial expansion 9 | 10 | % This file is from matlabtools.googlecode.com 11 | 12 | 13 | [pp.standardizeX, pp.rescaleX, pp.kernelFn, pp.poly, pp.addOnes] = process_options(varargin, ... 14 | 'standardizeX', false, 'rescaleX', false, 'kernelFn', [], 'poly', [], ... 15 | 'addOnes', false); 16 | 17 | 18 | end 19 | -------------------------------------------------------------------------------- /util/approxeq.m: -------------------------------------------------------------------------------- 1 | function p = approxeq(a, b, tol, rel) 2 | % Are a and b approximately equal (to within a specified tolerance)? 3 | % p = approxeq(a, b, thresh) 4 | % 'tol' defaults to 1e-3. 5 | % p(i) = 1 iff abs(a(i) - b(i)) < thresh 6 | % 7 | % p = approxeq(a, b, thresh, 1) 8 | % p(i) = 1 iff abs(a(i)-b(i))/abs(a(i)) < thresh 9 | 10 | % This file is from matlabtools.googlecode.com 11 | 12 | 13 | if nargin < 3, tol = 1e-2; end 14 | if nargin < 4, rel = 0; end 15 | 16 | a = a(:); 17 | b = b(:); 18 | if length(a) ~= length(b) 19 | p = false; 20 | return; 21 | end 22 | d = abs(a-b); 23 | if rel 24 | p = ~any( (d ./ (abs(a)+eps)) > tol); 25 | else 26 | p = ~any(d > tol); 27 | end 28 | 29 | end 30 | -------------------------------------------------------------------------------- /metaTools/isfunction.m: -------------------------------------------------------------------------------- 1 | function tf = isfunction(fname) 2 | % Return true if the specified file is a matlab function, (not a script). 3 | % 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | if endswith(fname, '.m') 9 | fname = fname(1:end-2); 10 | end 11 | 12 | w = which(fname); 13 | if startswith(w, 'built-in') 14 | tf = true; 15 | return; 16 | end 17 | 18 | if ~exist(fname, 'file') 19 | tf = false; 20 | return; 21 | end 22 | 23 | if isclassdef(fname) 24 | tf = false; 25 | return; 26 | end 27 | 28 | text = filterCell(getText(fname), @(s)~startswith(strtrim(s), '%')); 29 | tf = any( cellfun(@(s)startswith(strtrim(s), 'function'), text)); 30 | 31 | 32 | end 33 | -------------------------------------------------------------------------------- /metaTools/findAllFilesWithTag.m: -------------------------------------------------------------------------------- 1 | function m = findAllFilesWithTag(tag, returnFullPath, root) 2 | % Find all of the files in the PMTK directory structure with a certain tag 3 | % See also pmtkTagReport 4 | %% 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | if nargin < 2, returnFullPath = false; end 9 | if nargin < 3, root = pmtk3Root(); end 10 | if tag(1) == '%', tag(1) = []; end 11 | tag = strtrim(tag); 12 | allfiles = mfiles(root, 'useFullPath', returnFullPath); 13 | m = {}; 14 | for i=1:numel(allfiles) 15 | fpath = which(allfiles{i}); 16 | if isempty(fpath), continue; end 17 | if(hasTag(fpath, tag)) 18 | m = [m, allfiles{i}]; %#ok 19 | end 20 | end 21 | m = m'; 22 | end 23 | -------------------------------------------------------------------------------- /metaTools/removeComments.m: -------------------------------------------------------------------------------- 1 | function S = removeComments(S) 2 | % Remove comments from a cell array storing mfile text. 3 | % The getText function returns the text of an mfile as a cell array, this 4 | % function removes comments and blank lines from this cell array. 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | 9 | blockCommentStart = cellfind(S, '%{'); 10 | blockCommentEnd = cellfind(S, '%}'); 11 | ndx = []; 12 | for i=1:numel(blockCommentStart) 13 | ndx = [ndx, blockCommentStart(i):blockCommentEnd(i)]; %#ok 14 | end 15 | S(ndx) = []; 16 | 17 | 18 | filter = @(str)~startswith(strtrim(str), '%') && ~isempty(strtrim(str)); 19 | S = filterCell(S, filter); 20 | 21 | 22 | 23 | 24 | end 25 | -------------------------------------------------------------------------------- /stats/mk_multi_index.m: -------------------------------------------------------------------------------- 1 | function index = mk_multi_index(n, dims, vals) 2 | % Compute the indices of the submatrix where dims(i)=vals(i) 3 | % index = mk_multi_index(n, dims, vals) 4 | % 5 | % Example: 6 | % index = mk_multi_index(3, [1 3], [3 2]) 7 | % gives index = {3, ':', 2}, which will select out dim 1 = 3 and dim 3 = 2 8 | % So if A(:,:,1)=[1 2;3 4; 5 6]; A(:,:,2)=[7 8; 9 10; 11 12] 9 | % then A(index{:}) = [11 12]: 10 | 11 | % This file is from matlabtools.googlecode.com 12 | 13 | 14 | if n==0 15 | index = { 1 }; 16 | return; 17 | end 18 | 19 | index = cell(1,n); 20 | for i=1:n 21 | index{i} = ':'; 22 | end 23 | for i=1:length(dims) 24 | index{dims(i)} = vals(i); 25 | end 26 | 27 | end 28 | -------------------------------------------------------------------------------- /stats/sqDistance.m: -------------------------------------------------------------------------------- 1 | function d = sqDistance(p, q, pSOS, qSOS) 2 | % Efficiently compute squared euclidean distances between sets of vectors 3 | % 4 | % Compute the squared Euclidean distances between every d-dimensional point 5 | % in p to every d-dimensional point in q. Both p and q are 6 | % npoints-by-ndimensions. 7 | % 8 | % d(i, j) = sum((p(i, :) - q(j, :)).^2)s 9 | % 10 | % pSOS = sum(p.^2, 2) and is calculated if not specified 11 | % qSOS = sum(q.^2, 2) and is calculated if not specified 12 | % 13 | %% 14 | 15 | % This file is from matlabtools.googlecode.com 16 | 17 | if(nargin < 4) 18 | pSOS = sum(p.^2, 2); 19 | qSOS = sum(q.^2, 2); 20 | end 21 | d = bsxfun(@plus, pSOS, qSOS') - 2*p*q'; 22 | end 23 | -------------------------------------------------------------------------------- /stats/text2stream.m: -------------------------------------------------------------------------------- 1 | function [stream, cleanString] = text2stream(string) 2 | % Converts a charachter array to an array of integers 3 | % corresponding to the letters and spaces in the string. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | string = lower(string); 9 | letters = double('a':'z'); 10 | space = double(' '); 11 | v = double(lower(string)); 12 | alphaMask = (v >= min(letters) & v <= max(letters)); 13 | spaceMask = (v == space); 14 | valid = alphaMask | spaceMask; 15 | v(~valid) = space; 16 | spaceMask = (v == space); 17 | v(alphaMask) = v(alphaMask) - min(letters) + 1; 18 | v(spaceMask) = 27; 19 | 20 | stream = v; 21 | alphabet = ['a':'z' ' ']; 22 | cleanString = alphabet(stream); 23 | -------------------------------------------------------------------------------- /util/zipmats.m: -------------------------------------------------------------------------------- 1 | function z = zipmats(varargin) 2 | % Zip up multiple numeric vectors into one cell array 3 | % Takes in an arbitrary number, K, of numeric vectors, v1, v2,...vj,...,vk 4 | % all of the same size, N-by-1, (or 1-by-N) and returns a cell array z, 5 | % such that z{i}(j) = vj(i) for all i in 1:N and all j in 1:K. 6 | % 7 | % Example: 8 | % z = zipmats(1:3 , 4:6 , 7:9 , 100:102) % extends to any number of inputs 9 | % celldisp(z) 10 | % z{1} = 11 | % 1 4 7 100 12 | % z{2} = 13 | % 2 5 8 101 14 | % z{3} = 15 | % 3 6 9 102 16 | 17 | % This file is from matlabtools.googlecode.com 18 | 19 | 20 | z = mat2cellRows(cell2mat(cellfuncell(@(c)colvec(c), varargin))); 21 | end 22 | -------------------------------------------------------------------------------- /util/sizePMTK.m: -------------------------------------------------------------------------------- 1 | function sz = sizePMTK(M) 2 | % Like the built-in size, except it returns n if M is a vector of length n, and 1 if M is a scalar 3 | % 4 | % The behavior is best explained by examples 5 | % - M = rand(1,1), sizePMTK(M) = 1, size(M) = [1 1] 6 | % - M = rand(2,1), sizePMTK(M) = 2, size(M) = [2 1] 7 | % - M = rand(1,2), sizePMTK(M) = 2, size(M) = [1 2] 8 | % - M = rand(2,2,1), sizePMTK(M) = [2 2], size(M) = [2 2] 9 | % - M = rand(1,2,1), sizePMTK(M) = 2, size(M) = [1 2] 10 | 11 | % This file is from matlabtools.googlecode.com 12 | 13 | 14 | 15 | 16 | if isempty(M) 17 | sz = 0; 18 | elseif isvector(M) 19 | sz = numel(M); 20 | else 21 | sz = size(M); 22 | end 23 | 24 | end 25 | -------------------------------------------------------------------------------- /metaTools/gatherTagText.m: -------------------------------------------------------------------------------- 1 | function C = gatherTagText(R, tag, fileNdx) 2 | %% Gather the tag text from R=tagReport() into a cell array 3 | % C{i} is the text associated with the specified tag for 4 | % R.files{fileNdx(i)}, and is blank if the file has not such tag. 5 | % If fileNdx is not specified, all files are searched. 6 | %% 7 | 8 | % This file is from matlabtools.googlecode.com 9 | 10 | if nargin < 3 11 | fileNdx = 1:numel(R.files); 12 | end 13 | 14 | nfiles = numel(fileNdx); 15 | C = cell(nfiles, 1); 16 | tags = R.tags(fileNdx); 17 | tagtext = R.tagtext(fileNdx); 18 | for i=1:nfiles 19 | ndx = cellfind(tags{i}, tag); 20 | if isempty(ndx), continue; end 21 | C(i) = tagtext{i}(ndx); 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /stats/makePolyData.m: -------------------------------------------------------------------------------- 1 | function [xtrain, ytrain, xtest, ytest] = makePolyData(n) 2 | 3 | %error('deprecated') 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | % based on code by Romain Thibaux 9 | % (Lecture 2 from http://www.cs.berkeley.edu/~asimma/294-fall06/) 10 | 11 | %if nargin < 1, rng = 0:20; end 12 | if nargin < 1, n = 21; end 13 | 14 | randn('state', 654321); 15 | w = [-1.5; 1/9]; 16 | %xtrain = (0:20)'; 17 | xtrain = linspace(0,20,n)'; 18 | xtest = (0:0.1:20)'; 19 | n = length(xtrain); 20 | sigma2 = 4; 21 | ytrueTrain = w(1)*xtrain+w(2)*xtrain.^2; 22 | ytrain = ytrueTrain+sqrt(sigma2)*randn(n,1); 23 | 24 | ytrueTest = w(1)*xtest+w(2)*xtest.^2; 25 | ytest = ytrueTest +sqrt(sigma2)*randn(length(xtest),1); 26 | -------------------------------------------------------------------------------- /util/createStruct.m: -------------------------------------------------------------------------------- 1 | function s = createStruct(names, values) 2 | %% Create a struct from two separate lists: names, and values. 3 | % Usually to create a struct you have to interleave the names and values 4 | % as in struct('name1',val1,'name2',val2,...) - here you can pass in the 5 | % names and values as two cell arrays. If values is not specified, it just 6 | % assigns {}. 7 | 8 | % This file is from matlabtools.googlecode.com 9 | 10 | s = struct; 11 | if(nargin < 2) 12 | for i=1:numel(names); 13 | s.(names{i}) = {}; 14 | end 15 | else 16 | if(isnumeric(values)) 17 | values = num2cell(values); 18 | end 19 | for i=1:numel(names); 20 | s.(names{i}) = values{i}; 21 | end 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /util/unSandwich.m: -------------------------------------------------------------------------------- 1 | function T = unSandwich(str, leftMarker, rightMarker) 2 | %% Like tokenize, but extracts text between 'sandwiching' markers 3 | % 4 | %% Output 5 | % meat - a (possibly empty) cell array of the unsandwiched tokens 6 | %% Example 7 | % 8 | % meat = unSandwich('please see or for details.', '<', '>') 9 | % 10 | % meat = {'mywebsite.html', 'wikipedia.org'} 11 | %% 12 | 13 | % This file is from matlabtools.googlecode.com 14 | 15 | toks = tokenize(str, [leftMarker, rightMarker]); 16 | if numel(toks) < 2 17 | T = {}; 18 | else 19 | remaining = str(find(str==rightMarker, 1, 'first')+1:end); 20 | T = [toks(2), unSandwich(remaining, leftMarker, rightMarker)] ; 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /stats/bestPermutation.m: -------------------------------------------------------------------------------- 1 | function [p, nerrs] = bestPermutation(source, target) 2 | % Permute labels to minimize the number of mismatches with a target 3 | % 4 | %% Example 5 | % p = bestPermutation([1 1 1 2 2 2 3 3 3], [2 2 3 1 1 1 3 3 2]) 6 | % p = 7 | % 2 2 2 1 1 1 3 3 3 8 | %% 9 | 10 | % This file is from matlabtools.googlecode.com 11 | 12 | nlabels = nunique([rowvec(source), rowvec(target)]); 13 | allperms = perms(1:nlabels); 14 | errs = zeros(1, size(allperms, 1)); 15 | 16 | for i=1:size(allperms, 1); 17 | perm = allperms(i, source); 18 | errs(i) = sum(perm ~= target); 19 | end 20 | 21 | bestidx = minidx(errs); 22 | p = allperms(bestidx, source); 23 | nerrs = errs(bestidx); 24 | 25 | end 26 | -------------------------------------------------------------------------------- /util/enumerate.m: -------------------------------------------------------------------------------- 1 | function enum = enumerate(strings) 2 | % Create an inverted map from strings to their index values in a list 3 | % 4 | % If any string is not a valid field name, it is made valid using 5 | % genvarname(), therefore it is good practice to index into enum with 6 | % enum.(genvarname(name)). 7 | % 8 | % EXAMPLE: 9 | % 10 | % enum = enumerate({'alpha','beta','gamma','delta','epsilon','zeta','eta'}) 11 | % enum = 12 | % alpha: 1 13 | % beta: 2 14 | % gamma: 3 15 | % delta: 4 16 | % epsilon: 5 17 | % zeta: 6 18 | % eta: 7 19 | 20 | % This file is from matlabtools.googlecode.com 21 | 22 | 23 | enum = createStruct(cellfuncell(@genvarname, strings), num2cell(1:numel(strings))); 24 | end 25 | -------------------------------------------------------------------------------- /util/structure.m: -------------------------------------------------------------------------------- 1 | function S = structure(varargin) 2 | % Create a struct directly from variables, without having to provide names 3 | % The current names of the variables are used as the structure fields. 4 | % 5 | % *** does not support anonymous variables as in structure(25, 2+3), etc *** 6 | % 7 | %% Example 8 | % 9 | % mu = zeros(1, 10); 10 | % Sigma = randpd(10); 11 | % pi = normalize(ones(1, 10)); 12 | % model = structure(mu, Sigma, pi); 13 | % model 14 | % model = 15 | % mu: [0 0 0 0 0 0 0 0 0 0] 16 | % Sigma: [10x10 double] 17 | % pi: [1x10 double] 18 | %% 19 | 20 | % This file is from matlabtools.googlecode.com 21 | 22 | 23 | for i=1:nargin 24 | S.(inputname(i)) = varargin{i}; 25 | end 26 | 27 | 28 | end 29 | 30 | -------------------------------------------------------------------------------- /stats/make2dData.m: -------------------------------------------------------------------------------- 1 | function [data, labels] = make2dData(ndata, Nclasses) 2 | 3 | % Generate mixture of 2-3 Gaussians in two dimensional space 4 | % Based on dem2data from netlab 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | 9 | data = randn(ndata, 2); 10 | 11 | % Cluster centres 12 | c = [2.0, 3.5; 0.0, 0.0; 0.0, 2.0]; 13 | 14 | % Cluster standard deviations 15 | sd = 1*[1 1 1]; 16 | 17 | if Nclasses == 2 18 | prior = [0.5 0.5]; 19 | else 20 | prior = [0.3 0.3 0.4]; 21 | end 22 | 23 | ndx = partitionData(1:ndata, prior); 24 | for i=1:Nclasses 25 | labels(ndx{i}) = i; 26 | % shift and scale data for each class 27 | data(ndx{i}, 1) = data(ndx{i}, 1) * sd(i) + c(i,1); 28 | data(ndx{i}, 2) = data(ndx{i}, 2) * sd(i) + c(i,2); 29 | end 30 | -------------------------------------------------------------------------------- /graphics/plotSurface.m: -------------------------------------------------------------------------------- 1 | function [h, p] = plotSurface(fn, xyRange, varargin) 2 | % Plot the surface of the function 3 | % evalatuated at xyRange = [xmin xmax ymin ymax]. 4 | % 5 | % All other args (varargin) are passed directly to the surf function, 6 | % except for 'npoints', which is by default 100. 7 | %% 8 | 9 | % This file is from matlabtools.googlecode.com 10 | 11 | [npoints, args] = process_options(varargin, 'npoints', 100); 12 | if nargin < 2 13 | xyRange = [-10 10 -10 10]; 14 | end 15 | [X1, X2] = meshgrid( linspace(xyRange(1), xyRange(2), npoints)', ... 16 | linspace(xyRange(3), xyRange(4), npoints)' ); 17 | nr = size(X1, 1); nc = size(X2, 1); 18 | p = reshape(fn([X1(:) X2(:)]), nr, nc); 19 | p(~isfinite(p)) = NaN; 20 | h = surf(X1, X2, p, args{:}); 21 | end 22 | -------------------------------------------------------------------------------- /stats/createXORdata.m: -------------------------------------------------------------------------------- 1 | function [X, y] = createXORdata(doplot) 2 | %% Generate noisy XOR data 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | if nargin < 1, doplot = false; end 7 | setSeed(0); 8 | off1 = gaussSample(struct('mu', [1, 1], 'Sigma', 0.5*eye(2)), 20); 9 | off2 = gaussSample(struct('mu', [5, 5], 'Sigma', 0.5*eye(2)), 20); 10 | on1 = gaussSample(struct('mu', [1, 5], 'Sigma', 0.5*eye(2)), 20); 11 | on2 = gaussSample(struct('mu', [5, 1], 'Sigma', 0.5*eye(2)), 20); 12 | X = [off1; off2; on1; on2]; 13 | y = [zeros(size(off1, 1) + size(off2, 1), 1); ones(size(on1, 1) + size(on2, 1), 1)]; 14 | if doplot 15 | plot(X(y==0, 1), X(y==0, 2), 'ob', 'MarkerSize', 8); hold on 16 | plot(X(y==1, 1), X(y==1, 2), '+r', 'MarkerSize', 8); 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /stats/normalize.m: -------------------------------------------------------------------------------- 1 | function [A, z] = normalize(A, dim) 2 | % Make the entries of a (multidimensional) array sum to 1 3 | % [A, z] = normalize(A) normalize the whole array, where z is the normalizing constant 4 | % [A, z] = normalize(A, dim) 5 | % If dim is specified, we normalize the specified dimension only. 6 | % dim=1 means each column sums to one 7 | % dim=2 means each row sums to one 8 | % 9 | %% 10 | % Set any zeros to one before dividing. 11 | % This is valid, since s=0 iff all A(i)=0, so 12 | % we will get 0/1=0 13 | 14 | % This file is from matlabtools.googlecode.com 15 | 16 | if(nargin < 2) 17 | z = sum(A(:)); 18 | z(z==0) = 1; 19 | A = A./z; 20 | else 21 | z = sum(A, dim); 22 | z(z==0) = 1; 23 | A = bsxfun(@rdivide, A, z); 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /stats/partitionData.m: -------------------------------------------------------------------------------- 1 | function indices = partitionData(data, pc) 2 | % Partition a vector of data into sets of different sizes 3 | % function indices = partitionData(data, pc) 4 | % 5 | % Example: 6 | % indices =partitionData(1:105,[0.3,0.2,0.5]) 7 | % a= 1:31, b=32:52, c=53:105 (last bin gets all the left over) 8 | 9 | % This file is from matlabtools.googlecode.com 10 | 11 | 12 | 13 | Npartitions = length(pc); 14 | perm = data; 15 | Ndata = length(data); 16 | ndx = 1; 17 | for i=1:Npartitions 18 | Nbin(i) = fix(Ndata*pc(i)); 19 | low(i) = ndx; 20 | if i==Npartitions 21 | high(i) = Ndata; 22 | else 23 | high(i) = low(i)+Nbin(i)-1; 24 | end 25 | indices{i} = perm(low(i):high(i)); 26 | ndx = ndx+Nbin(i); 27 | end 28 | 29 | 30 | end 31 | -------------------------------------------------------------------------------- /metaTools/previewPublished.m: -------------------------------------------------------------------------------- 1 | function previewPublished(fname, evalCode, outputDir) 2 | %% Preview what the published result of the demo will look like 3 | % 4 | % If evalCode is set to false, (default true), the demo is not run and only 5 | % text is published. 6 | %% Example 7 | % publishPreview mixGaussVbDemoFaithful 8 | % PMTKneedsMatlab 9 | 10 | % This file is from matlabtools.googlecode.com 11 | 12 | close all; 13 | SetDefaultValue(2, 'evalCode', true); 14 | SetDefaultValue(3, 'outputDir', tempdir()); 15 | 16 | options.evalCode = evalCode; 17 | options.outputDir = outputDir; 18 | options.format = 'html'; 19 | options.createThumbnail = false; 20 | publish(which(fname), options); 21 | web(fullfile(outputDir, [filenames(fname), '.html'])); 22 | close all; 23 | 24 | 25 | end 26 | -------------------------------------------------------------------------------- /stats/classConfMat.m: -------------------------------------------------------------------------------- 1 | function M = classConfMat(ytrue, yhat) 2 | % Make a class confusion matrix 3 | % M(truth, est) = num times truth gets labeled as est 4 | % result is an array with starting index of 1, so you have to figure out 5 | % labels separately. It will do all possible integer classes, i.e. if you 6 | % have two classes 1 and 1000 don't use this function, however, if you have 7 | % classes 1:9 but are missing class 7 for example, it will do the right 8 | % thing 9 | 10 | % This file is from matlabtools.googlecode.com 11 | 12 | C = max(unique(ytrue)); 13 | Cmin = min(unique(ytrue)); 14 | Ccount=C-Cmin+1; 15 | M = zeros(Ccount,Ccount); 16 | for i=1:Ccount 17 | for j=1:Ccount 18 | M(i,j) = sum((ytrue==(Cmin+i-1)).*(yhat==(Cmin+j-1))); 19 | end 20 | end 21 | 22 | 23 | 24 | end 25 | -------------------------------------------------------------------------------- /stats/makeModelSpace.m: -------------------------------------------------------------------------------- 1 | function models = makeModelSpace(varargin) 2 | % Return a cell array of every combination of the inputs 3 | % Pass in one argument per dimension. Returns a cell array of every 4 | % combination of values. 5 | % 6 | % Example: 7 | % 8 | % lambdaRange = logspace(0, 100, 10); 9 | % sigmaRange = linspace(0, 10, 10); 10 | % 11 | % allCombinations = makeModelSpace(lambdaRange, sigmaRange) 12 | % 13 | % Supports more than 2 dimensions, i.e. makeModelSpace(1:3, 2:4, 7:9, 2:3) 14 | %% 15 | 16 | % This file is from matlabtools.googlecode.com 17 | 18 | if(nargin == 1) 19 | space = varargin{1}'; 20 | else 21 | space = gridSpace(varargin{:}); 22 | end 23 | models = cell(size(space,1),1); 24 | for i=1:size(space,1) 25 | models{i} = num2cell(space(i,:)); 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /metaTools/getText.m: -------------------------------------------------------------------------------- 1 | function text = getText(textFile) 2 | % Extract the text from a file. The output is a cell array - each cell is a line 3 | % from the file. See also writeText() 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | text = {}; 8 | w = which(textFile); 9 | if ~isempty(w) 10 | textFile = w; 11 | end 12 | 13 | fid = fopen(textFile); 14 | if(fid < 0) 15 | fprintf('Sorry could not open %s\n',textFile); 16 | return; 17 | end 18 | alloc = cell(5000, 1); 19 | text = alloc; 20 | i = 1; 21 | while(true) 22 | tline = fgetl(fid); 23 | if ~ischar(tline) 24 | break; 25 | end 26 | text{i} = tline; 27 | i = i+1; 28 | if i > numel(text) 29 | text = [text; alloc]; %#ok 30 | end 31 | end 32 | text = text(1:i-1); 33 | fclose(fid); 34 | end 35 | -------------------------------------------------------------------------------- /util/bsxTable.m: -------------------------------------------------------------------------------- 1 | function Tbig = bsxTable(fn, Tbig, Tsmall, bigdom, smalldom) 2 | %% Apply a binary function to two multidimensional vectors using bsxfun 3 | % reshaping and virtually expanding the smaller table as needed 4 | % 5 | % The tables are matched up according to smalldom and bigdom 6 | % smalldom must be a subset (but not necessarily a subsequence) of bigdom 7 | % 8 | % 9 | %% 10 | 11 | % This file is from matlabtools.googlecode.com 12 | 13 | smallsz = sizePMTK(Tsmall); 14 | if isequal(bigdom, smalldom) 15 | Tbig = fn(Tbig, Tsmall); 16 | else 17 | nbig = numel(bigdom); 18 | ndx = lookupIndices(smalldom, bigdom); 19 | sz = ones(1, nbig); 20 | sz(ndx) = smallsz; 21 | Tsmall = reshape(Tsmall, [sz 1]); 22 | Tbig = bsxfun(fn, Tbig, Tsmall); 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /util/isprefix.m: -------------------------------------------------------------------------------- 1 | function p = isprefix(short, long) 2 | % Return true iff the first input is a prefix of the second 3 | % The second arg may also be a cell array of strings, in which case, each 4 | % is tested. CASE SENSITIVE! 5 | % 6 | % If the second argument is not a string, p = false, it does not error. 7 | % 8 | % EXAMPLES: 9 | % 10 | % isprefix('foo','foobar') 11 | % ans = 12 | % 1 13 | % 14 | %isprefix('test_',{'test_MvnDist','test_DiscreteDist','UnitTest'}) 15 | %ans = 16 | % 1 1 0 17 | 18 | % This file is from matlabtools.googlecode.com 19 | 20 | error(nargchk(2,2,nargin)); 21 | if ischar(long) 22 | p = strncmp(long,short,length(short)); 23 | elseif iscell(long) 24 | p = cellfun(@(c)isprefix(short,c),long); 25 | else 26 | p = false; 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /graphics/gaussPlot2d.m: -------------------------------------------------------------------------------- 1 | function h=gaussPlot2d(mu, Sigma, varargin) 2 | % Plot an ellipse representing the covariance matrix of a Gaussian 3 | % 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | if size(Sigma) ~= [2 2], error('Sigma must be a 2 by 2 matrix'); end 8 | [color, plotMarker] = process_options(varargin, 'color', 'r', 'plotMarker', true); 9 | 10 | mu = mu(:); 11 | [U, D] = eig(Sigma); 12 | n = 100; 13 | t = linspace(0, 2*pi, n); 14 | xy = [cos(t); sin(t)]; 15 | %k = sqrt(chi2inv(0.95, 2)); % 5.99 16 | k = sqrt(6); 17 | w = (k * U * sqrt(D)) * xy; 18 | z = repmat(mu, [1 n]) + w; 19 | h = plot(z(1, :), z(2, :), color, 'linewidth', 2); 20 | hold on 21 | if plotMarker 22 | hh=plot(mu(1), mu(2), 'x'); 23 | set(hh,'color',color, 'linewidth', 2, 'markersize', 13); 24 | end 25 | %axis('equal'); 26 | end 27 | -------------------------------------------------------------------------------- /util/prepareArgs.m: -------------------------------------------------------------------------------- 1 | function out = prepareArgs(args) 2 | % Convert a struct into a name/value cell array for use by process_options 3 | % 4 | % Prepare varargin args for process_options by converting a struct in args{1} 5 | % into a name/value pair cell array. If args{1} is not a struct, args 6 | % is left unchanged. 7 | % Example: 8 | % opts.maxIter = 100; 9 | % opts.verbose = true; 10 | % foo(opts) 11 | % 12 | % This is equivalent to calling 13 | % foo('maxiter', 100, 'verbose', true) 14 | 15 | % This file is from matlabtools.googlecode.com 16 | 17 | 18 | if isstruct(args) 19 | out = interweave(fieldnames(args), struct2cell(args)); 20 | elseif ~isempty(args) && isstruct(args{1}) 21 | out = interweave(fieldnames(args{1}), struct2cell(args{1})); 22 | else 23 | out = args; 24 | end 25 | 26 | 27 | 28 | 29 | end 30 | -------------------------------------------------------------------------------- /metaTools/dirinfo.m: -------------------------------------------------------------------------------- 1 | function info = dirinfo(directory) 2 | % Collect information about the files in a directory structure 3 | %Recursively descend through the directory structure, starting at the 4 | %specified directory and collect information into a struct array with 5 | %fields, path, m, mat, mex, mdl, p, classes, packages. This is effectively 6 | %a recursive version of the built in "what" command. 7 | 8 | % This file is from matlabtools.googlecode.com 9 | 10 | 11 | if nargin == 0 12 | directory = '.'; 13 | end 14 | 15 | info = what(directory); 16 | flist = dir(directory); 17 | dlist = {flist([flist.isdir]).name}; 18 | for i=1:numel(dlist) 19 | dirname = dlist{i}; 20 | if(~strcmp(dirname,'.') && ~strcmp(dirname,'..')) 21 | info = [info, dirinfo([directory,'\',dirname])]; %#ok 22 | end 23 | end 24 | 25 | end 26 | -------------------------------------------------------------------------------- /metaTools/showImmediateToolboxDependencies.m: -------------------------------------------------------------------------------- 1 | function showImmediateToolboxDependencies(fname) 2 | %% Display the immediate toolbox dependencies of a function 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | if nargin == 0; 7 | fname = currentlyOpenFile(true); 8 | end 9 | 10 | D = depfun(fname, '-toponly', '-quiet'); 11 | [TB, NTB] = partitionCell(D, ... 12 | @(c)~startswith(c, fullfile(matlabroot, 'toolbox', 'matlab')) && ... 13 | startswith(c, fullfile(matlabroot, 'toolbox'))); 14 | 15 | if isempty(TB) 16 | fprintf('NO IMMEDIATE TOOLBOX DEPENDENCIES\n'); 17 | else 18 | fprintf('**** TOOLBOX DEPENDENCIES **** \n'); 19 | START = length(fullfile(matlabroot, 'toolbox'))+2; 20 | disp(cellfuncell(@(c)c(START:end), TB)); 21 | fprintf('******************************\n'); 22 | end 23 | end 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /graphics/gridSpace.m: -------------------------------------------------------------------------------- 1 | function g = gridSpace(varargin) 2 | % Similar to built in ndgrid except the output g is a single matrix, regardless 3 | % of the number of inputs. Suppose [a,b,c] = ndgrid(1:10,1:10,1:10), if 4 | % g = gridSpace(1:10,1:10,1:10), then g = [a(:),b(:),c(:)]; 5 | % 6 | 7 | % This file is from matlabtools.googlecode.com 8 | 9 | 10 | 11 | if nargin==1, varargin = repmat(varargin,[1 2]); end 12 | nout = numel(varargin); 13 | for i=length(varargin):-1:1, 14 | siz(i) = numel(varargin{i}); 15 | end 16 | 17 | g = zeros(prod(siz),nout); 18 | for i=1:nout, 19 | x = varargin{i}(:); % Extract and reshape as a vector. 20 | s = siz; s(i) = []; % Remove i-th dimension 21 | x = reshape(x(:,ones(1,prod(s))),[length(x) s]); % Expand x 22 | x = permute(x,[2:i 1 i+1:nout]); % Permute to i'th dimension 23 | g(:,i) = x(:); 24 | end 25 | 26 | end 27 | -------------------------------------------------------------------------------- /stats/preprocessorApplyToTest.m: -------------------------------------------------------------------------------- 1 | function [X] = preprocessorApplyToTest(preproc, X) 2 | % Transform the test data in the same way as the training data 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | if isempty(preproc), return; end 8 | 9 | if isfield(preproc, 'Xmu') 10 | X = centerCols(X, preproc.Xmu); 11 | end 12 | if isfield(preproc, 'Xstnd') 13 | X = mkUnitVariance(X, preproc.Xstnd); 14 | end 15 | if isfield(preproc, 'Xscale') 16 | X = rescaleData(X, preproc.Xscale(1), preproc.Xscale(2)); 17 | end 18 | if isfield(preproc, 'kernelFn') && ~isempty(preproc.kernelFn) 19 | X = preproc.kernelFn(X, preproc.basis); 20 | end 21 | if isfield(preproc, 'poly') && ~isempty(preproc.poly) 22 | X = degexpand(X, preproc.poly, false); 23 | end 24 | if isfield(preproc, 'addOnes') && preproc.addOnes 25 | X = addOnes(X); 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /metaTools/getFileModificationDate.m: -------------------------------------------------------------------------------- 1 | function [datestr, time] = getFileModificationDate(file) 2 | % Return the file modification date for the specified file. 3 | % 4 | %% Example 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | 9 | d = dir(file); 10 | toks = tokenize(d.date, ' '); 11 | [datestr, time] = toks{:}; 12 | %{ 13 | [err, raw] = system(sprintf('dir /TC %s', file)); 14 | raw = cellfuncell(@strtrim, tokenize(raw, '\n')); 15 | raw = filterCell(raw, @(c)~isempty(c)); 16 | raw = raw{cellfun(@(c)~isempty(c), (regexp(raw, '\d\d\/\d\d/\d\d\d\d')))}; 17 | toks = tokenize(raw, ' '); 18 | datestr = catString(toks(1:3), ' '); 19 | if nargout > 1 20 | toks = tokenize(raw, '/ '); 21 | day = str2num(toks{1}); 22 | month = str2num(toks{2}); 23 | year = str2num(toks{3}); 24 | time = catString(toks(4:5), ' '); 25 | end 26 | %} 27 | end 28 | -------------------------------------------------------------------------------- /graphics/plotConvDiagnostics.m: -------------------------------------------------------------------------------- 1 | function plotConvDiagnostics(X, ttl) 2 | % Plot trace plot, smoothed trace plot, and ACF of 1d quantity 3 | % X(samples, chain/seed) 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | if nargin < 2, ttl = ''; end 8 | nseeds = size(X,2); 9 | colors = {'r', 'g', 'b', 'k'}; 10 | 11 | % Trace plots 12 | %h=figure; set(h,'name', ttl); 13 | figure; 14 | hold on; 15 | for i=1:nseeds 16 | plot(X(:,i), colors{i}); 17 | end 18 | Rhat = epsr(X(:,:)); 19 | title(sprintf('%s, Rhat = %5.3f', ttl, Rhat)) 20 | 21 | % Smoothed trace plots 22 | figure; hold on 23 | for i=1:nseeds 24 | movavg = filter(repmat(1/50,50,1), 1, X(:,i)); 25 | plot(movavg, colors{i}); 26 | end 27 | title(sprintf('%s, Rhat = %5.3f', ttl, Rhat)) 28 | 29 | % Plot auto correlation function for 1 chain 30 | figure; 31 | stem(acf(X(:,1), 20)); 32 | title(ttl) 33 | end 34 | 35 | -------------------------------------------------------------------------------- /oop/isabstract.m: -------------------------------------------------------------------------------- 1 | function tf = isabstract(className) 2 | % Return true iff the class is abstract 3 | % PMTKneedsMatlab 2008 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | if hasTag(which(className),'%PMTKabstract') 9 | tf = true; return; 10 | end 11 | 12 | tf = false; 13 | metaInfo = meta.class.fromName(className); 14 | if(numel(metaInfo) == 0) 15 | fprintf('%s is not a class.\n',className); 16 | return; 17 | end 18 | 19 | methods = metaInfo.Methods; 20 | props = metaInfo.Properties; 21 | for i=1:numel(methods) 22 | if methods{i}.Abstract 23 | tf = true; 24 | return; 25 | end 26 | end 27 | 28 | for i=1:numel(props) 29 | if props{i}.Abstract 30 | tf = true; 31 | return; 32 | end 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /metaTools/getFileSize.m: -------------------------------------------------------------------------------- 1 | function [s, b] = getFileSize(f) 2 | % Return the size of a file as a formatted string 3 | % The size is in bytes if less than a KB, KB if less than a MB, MB if less 4 | % than a GB, otherwise GB. The string includes the units. If the file 5 | % cannot be found, an empty string is returned. 6 | % 7 | %% Example 8 | % 9 | % s = getFileSize('mnistAll.mat') 10 | % s = 11 | % 11.3 MB 12 | %% 13 | 14 | % This file is from matlabtools.googlecode.com 15 | 16 | f = which(f); 17 | if isempty(f) 18 | s = f; 19 | return 20 | end 21 | d = dir(f); 22 | b = d.bytes; 23 | kb = b/1024; 24 | mb = kb/1024; 25 | gb = mb/1024; 26 | if gb > 1 27 | s = sprintf('%.1f GB', mb); 28 | elseif mb > 1 29 | s = sprintf('%.1f MB', mb); 30 | elseif kb > 1 31 | s = sprintf('%.1f KB', kb); 32 | else 33 | s = sprintf('%d B', b); 34 | end 35 | 36 | 37 | 38 | 39 | end 40 | -------------------------------------------------------------------------------- /stats/oneStdErrorRule.m: -------------------------------------------------------------------------------- 1 | function idx_opt = oneStdErrorRule(res_mean, res_std, dof) 2 | % We pick the model whose error is within one standard error of the lowest 3 | % We assume models are ordered from least complex to most complex 4 | % If not, pass in the dof field to figure out the right order 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | 9 | n = length(res_mean); 10 | if nargin < 3, dof = 1:n; end 11 | 12 | [sortedDof, perm] = sort(dof); % smallest dof first 13 | if ~isequal(dof, sortedDof) 14 | %fprintf('sorting so simplest model comes first\n') 15 | res_mean = res_mean(perm); 16 | res_std = res_std(perm); 17 | end 18 | 19 | [res_min idx_opt] = min(res_mean); 20 | limit = res_min + res_std(idx_opt); 21 | idx_opt2 = find(res_mean < limit, 1); 22 | if ~isempty(idx_opt2) 23 | idx_opt = idx_opt2; 24 | end 25 | idx_opt = perm(idx_opt); 26 | 27 | end 28 | -------------------------------------------------------------------------------- /util/replicate.m: -------------------------------------------------------------------------------- 1 | function Arep = replicate(A, Adims, sz) 2 | %% Replicate A along possibly multiple dimensions so that size(Arep) == sz 3 | % Adims indicates the dimensions in 1:numel(sz) that A currently contains. 4 | % 5 | % Replicate is like repmat but only copies where needed to achieve the 6 | % desired size. 7 | % 8 | %% Example 9 | % In this exmaple, suppose A's dimensions 1:3 map to Arep's dims [2 4 5] 10 | % We want Arep to be of size [4 3 2 4 2]. Notice that if sz = size(Arep) 11 | % then sz(Adims) == size(A) 12 | %% 13 | % A = rand(3, 4, 2); 14 | % Adims = [2 4 5]; 15 | % Arep = replicate(A, [2 4 5], [4 3 2 4 2]); 16 | % sz = size(Arep) 17 | % sz = 18 | % 4 3 2 4 2 19 | % assert(isequal(sz(Adims), size(A))); 20 | %% 21 | 22 | % This file is from matlabtools.googlecode.com 23 | 24 | Arep = bsxTable(@times, onesPMTK(sz), A, 1:numel(sz), Adims); 25 | 26 | end 27 | -------------------------------------------------------------------------------- /metaTools/htmlTagKey.m: -------------------------------------------------------------------------------- 1 | function h = htmlTagKey(tableAlign) 2 | %% Return the html text for the demo/synopsis tag legend table 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | if nargin == 0, tableAlign = 'right'; end 7 | tableData = ... 8 | { 9 | 'S' , 'stats toolbox needed' , 'I' , 'interactive (user input required)' 10 | 'B' , 'bioinformatics toolbox needed' , 'M' , 'matlab needed (will not work in octave)' 11 | 'O' , 'optimization toolbox needed' , 'W' , 'windows needed (will not work in linux)' 12 | 'X' , 'currently broken' , '*' , 'slow (two stars indicates very slow)' 13 | }; 14 | h = htmlTable('data' , tableData , ... 15 | 'dosave' , false , ... 16 | 'doshow' , false , ... 17 | 'dataAlign' , 'left' , ... 18 | 'tableAlign' , tableAlign ... 19 | ); 20 | end 21 | -------------------------------------------------------------------------------- /graphics/plotmarkers.m: -------------------------------------------------------------------------------- 1 | function hh = plotmarkers(h, marker, col, frac) 2 | % add the specified marker to the figure handle at a sparse set (frac) of locations 3 | % Example usage 4 | %figure(1); clf 5 | %h1 = plot(1:1000, 'k-', 'linewidth', 3); hold on 6 | %hh1 = plotmarkers(h1, 'o') 7 | %h2 = plot(1000:-1:1, '-'); 8 | %hh2 = plotmarkers(h2, 's', [1 0.5 0.25], 0.05) 9 | %legend([hh1, hh2], {'foo', 'bar'}) 10 | 11 | % This file is from matlabtools.googlecode.com 12 | 13 | 14 | 15 | if nargin < 3, col = 'k'; end 16 | if nargin < 4, frac = 0.01; end 17 | style = '-'; 18 | 19 | obj=get(h); 20 | n = length(obj.XData); 21 | ndx = ceil(linspace(1,n,frac*n)); 22 | hold on 23 | %hh = plot(obj.XData(ndx), obj.YData(ndx), 'linestyle', style, 'color', col, 'marker', marker); 24 | hh = plot(obj.XData(ndx), obj.YData(ndx), '.', 'color', col); 25 | set(hh, 'marker', marker, 'markersize', 12); 26 | 27 | 28 | end 29 | -------------------------------------------------------------------------------- /graph/minSpanTreePrim.m: -------------------------------------------------------------------------------- 1 | function [A,cost] = minSpanTreePrimSimple(C) 2 | % set absent edges to infinite weight 3 | % See mstDemo for a test 4 | % See Aho, Hopcroft, Ullman "Data structures and algorithms" 1983, p235 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | n = length(C); 9 | A = zeros(n); 10 | closest = ones(1,n); 11 | used = zeros(1,n); % contains the members of U 12 | C = setdiag(C,inf); %disallow self arcs 13 | 14 | used(1) = 1; % start with node 1 15 | lowcost = C(1,:); 16 | cost = 0; 17 | 18 | for i=2:n 19 | k = argmin(lowcost); 20 | cost = cost + lowcost(k); 21 | A(k, closest(k)) = 1; 22 | A(closest(k), k) = 1; 23 | lowcost(k) = inf; 24 | used(k) = 1; 25 | NU = find(used==0); % not used = V\U 26 | for j=NU 27 | if (C(k,j) < lowcost(j)) 28 | lowcost(j) = C(k,j); 29 | closest(j) = k; 30 | end 31 | end 32 | end 33 | 34 | end 35 | -------------------------------------------------------------------------------- /metaTools/htmlTagString.m: -------------------------------------------------------------------------------- 1 | function tagstr = htmlTagString(tags) 2 | %% Generate the html tag string for the demo/ synopsis tables 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | tagstr = {}; 7 | if ismember('PMTKbroken' , tags), tagstr = [tagstr, {'X'} ]; end 8 | if ismember('PMTKneedsStatsToolbox', tags), tagstr = [tagstr, {'S'} ]; end 9 | if ismember('PMTKneedsOptimToolbox', tags), tagstr = [tagstr, {'O'} ]; end 10 | if ismember('PMTKneedsBioToolbox' , tags), tagstr = [tagstr, {'B'} ]; end 11 | if ismember('PMTKneedsMatlab' , tags), tagstr = [tagstr, {'M'} ]; end 12 | if ismember('PMTKinteractive' , tags), tagstr = [tagstr, {'I'} ]; end 13 | if ismember('PMTKslow' , tags), tagstr = [tagstr, {'*'} ]; end 14 | if ismember('PMTKreallySlow' , tags), tagstr = [tagstr, {'**'}]; end 15 | tagstr = catString(tagstr, ' '); 16 | if isempty(tagstr), tagstr = ' '; end 17 | end 18 | -------------------------------------------------------------------------------- /graphics/plotContour.m: -------------------------------------------------------------------------------- 1 | function [h, p, c] = plotContour(fn, xyRange, varargin) 2 | % Plot contours of the function 3 | % evalatuated at xyRange = [xmin xmax ymin ymax]. 4 | % 5 | % All other args (varargin) are passed directly to the contour function, 6 | % except for 'npoints', which is by default 100 and 'ncontours'. 7 | %% 8 | 9 | % This file is from matlabtools.googlecode.com 10 | 11 | [npoints, ncontours, args] = process_options(varargin, 'npoints', 100, 'ncontours', []); 12 | if nargin < 2 13 | xyRange = [-10 10 -10 10]; 14 | end 15 | npoints = 100; 16 | [X1, X2] = meshgrid( linspace(xyRange(1), xyRange(2), npoints)', ... 17 | linspace(xyRange(3), xyRange(4), npoints)' ); 18 | nr = size(X1, 1); nc = size(X2, 1); 19 | p = reshape(fn([X1(:) X2(:)]), nr, nc); 20 | if isempty(ncontours) 21 | [c, h] = contour(X1, X2, p, args{:}); 22 | else 23 | [c, h] = contour(X1, X2, p, ncontours, args{:}); 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /stats/covcond.m: -------------------------------------------------------------------------------- 1 | function [Sig,Lam] = covcond(c,a) 2 | % Generate a covariance matrix and its inverse with a given cond number 3 | % C and first direction A. 4 | %COVCOND covariance matrix with given condition number 5 | % [Sig,Lam] = covcond(C,A) generates covariance matrix and its 6 | % inverse with given cond number C and first direction A. 7 | 8 | % This file is from matlabtools.googlecode.com 9 | 10 | 11 | %PMTKauthor Marko Laine 12 | %PMTKurl http://www.helsinki.fi/~mjlaine/mcmc/ 13 | 14 | % $Revision: 1.2 $ $Date: 2007/08/10 10:49:52 $ 15 | 16 | % create orthogonal basis z, with 1 direction given by 'a' 17 | a = a(:); 18 | e = sort(1./linspace(c,1,length(a))); 19 | a(1) = a(1) + sign(a(1)) * norm(a); %the Householder trick 20 | z = eye(length(a)) - 2.0/norm(a)^2*a*a'; 21 | Sig = z * diag(e) * z' ; % target covariance 22 | Lam = z * inv(diag(e)) * z'; % and its inverse 23 | 24 | end 25 | -------------------------------------------------------------------------------- /stats/degexpand.m: -------------------------------------------------------------------------------- 1 | function xx = degexpand(x, deg, addOnes) 2 | % Expand input vectors to contain powers of the input features 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | [n,m] = size(x); 8 | if nargin < 3, addOnes = 0; end 9 | 10 | xx = repmat(x, [1 1 deg]); 11 | degs = repmat(reshape(1:deg, [1 1 deg]), [n m]); 12 | xx = xx .^ degs; 13 | xx = reshape(xx, [n, m*deg]); 14 | 15 | if addOnes 16 | xx = [ones(n,1) xx]; 17 | end 18 | 19 | 20 | % Scale down to numbers in [-1,1] 21 | % xx = xx / diag(max(abs(xx))) ; 22 | 23 | % eg $x(n,1:p)$ goes to 24 | %[x(n,1:p) \;\; x(n,1:p).^2 \; \ldots \; x(n,1:p).^d] 25 | 26 | %x = [1 2 3; 27 | % 2 0.5 1.5; 28 | % 0 1 2]; 29 | %degexpand(x, 2) 30 | %ans = 31 | % 1.0000 2.0000 3.0000 1.0000 4.0000 9.0000 32 | % 2.0000 0.5000 1.5000 4.0000 0.2500 2.2500 33 | % 0 1.0000 2.0000 0 1.0000 4.0000 34 | 35 | 36 | end 37 | -------------------------------------------------------------------------------- /graph/mkRootedTree.m: -------------------------------------------------------------------------------- 1 | function [T, preorder] = mkRootedTree(adjMat, root) 2 | % Adjmat should be the adjacency matrix of an undirected tree 3 | % All arrows point away from the root (root defaults to 1) 4 | % T is a sparse matrix. 5 | % Also returns nodes in pre-order 6 | 7 | % This file is from matlabtools.googlecode.com 8 | 9 | if nargin < 2, root = 1; end 10 | n = length(adjMat); 11 | T = sparse(n,n); % not the same as T = sparse(n) ! 12 | 13 | %{ 14 | directed = 0; 15 | verbose = true; 16 | [d, preorder, postorder, hascycle, f, pred] = dfsPMTK(adjMat, root, directed); 17 | if hascycle 18 | warning('not a tree!') 19 | end 20 | %} 21 | 22 | [d dt ft pred] = dfs(adjMat,root,1); %#ok (gaimc package) 23 | % dt is discovery time, pred is predecessor in search 24 | dt(root) = 0; 25 | [junk, preorder]= sort(dt); 26 | preorder = rowvec(preorder); 27 | 28 | for i=1:length(pred) 29 | if pred(i)>0 30 | T(pred(i),i)=1; %#ok 31 | end 32 | end 33 | 34 | end 35 | -------------------------------------------------------------------------------- /graphics/printPmtkFigure.m: -------------------------------------------------------------------------------- 1 | function printPmtkFigure(filename) 2 | % print current figure to specified file in .eps and .pdf formats 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | if false 8 | % set to false to turn off printing 9 | printFolder = 'C:\kmurphy\dropbox\PML\Figures\pdfFigures'; 10 | %pdfcrop; 11 | %opts = struct('Color', 'rgb', 'Resolution', 1200); 12 | % try/catch not supported by old versions of matlab... 13 | %try 14 | fname = sprintf('%s/%s.pdf', printFolder, filename); 15 | fprintf('printing to %s\n', fname); 16 | if exist(fname,'file'), delete(fname); end % prevent export_fig from appending 17 | %exportfig(gcf, fname, opts, 'Format', 'pdf' ); 18 | set(gca,'Color','none') 19 | set(gcf,'Color','none') 20 | export_fig(fname) 21 | %catch ME 22 | % could silently return instead... 23 | % fprintf('could not print to %s/%s\n', printFolder, filename); 24 | %end 25 | end 26 | 27 | end 28 | -------------------------------------------------------------------------------- /metaTools/statsToolboxDependencies.m: -------------------------------------------------------------------------------- 1 | function statsToolboxDependencies(rootDir) 2 | % Generate an html table showing all of the stats toolbox functions used 3 | % by files in rootDir, (and subdirectories), along with the files that use 4 | % them. 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | cd(rootDir); 9 | R = deptoolbox('stats'); 10 | S = unique(vertcat(R.dependsOn{:})); 11 | F = cell(numel(S), 1); 12 | for i=1:numel(S) 13 | statsFn = S{i}; 14 | for j=1:numel(R.filename) 15 | if ismember(statsFn, R.dependsOn{j}) 16 | F{i} = insertEnd(R.filename{j}, F{i}); 17 | end 18 | end 19 | end 20 | S = cellfuncell(@(c)argout(2, @fileparts, c), S); 21 | F = cellfuncell(@(c)unique(c'), F); 22 | F = cellfunR(@(c)argout(2, @fileparts, c), F); 23 | perm = sortidx(cellfun(@numel, F), 'descend'); 24 | S = S(perm); 25 | F = F(perm); 26 | htmlTable('data', [S, F], 'colNames', {'STATS', rootDir},'dataAlign', 'left'); 27 | 28 | end 29 | -------------------------------------------------------------------------------- /oop/classesBFS.m: -------------------------------------------------------------------------------- 1 | function [classes,adjmat] = classesBFS(varargin) 2 | % Return a list of classes in breadth first search order 3 | % Same inputs as getClasses 4 | % PMTKneedsMatlab 2008 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | 9 | 10 | classes = getClasses(varargin{:}); 11 | if(isempty(classes)), fprintf('\nNo classes found in this directory.\n'); return; end 12 | classMap = enumerate(classes); 13 | adjmat = false(numel(classes)); 14 | for c=1:numel(classes) 15 | supers = cellfuncell(@(n)n.Name,meta.class.fromName(classes{c}).SuperClasses); 16 | for s=1:numel(supers) 17 | if ismember(supers{s},classes), adjmat(classMap.(supers{s}),classMap.(classes{c})) = true; end 18 | end 19 | end 20 | 21 | perm = topological_sort(adjmat); 22 | classes = classes(perm); 23 | adjmat = adjmat(perm,:); 24 | adjmat = adjmat(:,perm); 25 | 26 | 27 | 28 | end 29 | -------------------------------------------------------------------------------- /util/deconstruct.m: -------------------------------------------------------------------------------- 1 | function varargout = deconstruct(S) 2 | % Deconstruct a structure from the output arguments only 3 | % See also, structure(). 4 | %% Example 5 | % mu = zeros(1, 10); 6 | % Sigma = randpd(10); 7 | % pi = normalize(ones(1, 10)); 8 | % model = structure(mu, Sigma, pi); 9 | % 10 | % [mu, Sigma, pi] = deconstruct(model); % cannot be called from the command line. 11 | % 12 | % *** warning this function is not efficient *** 13 | 14 | % This file is from matlabtools.googlecode.com 15 | 16 | stack = dbstack('-completenames'); 17 | if numel(stack) < 2 18 | error('This function cannot be called from the command prompt'); 19 | end 20 | linenum = stack(2).line; 21 | fid = fopen(stack(2).file, 'r'); 22 | for i=1:linenum-1 23 | fgetl(fid); 24 | end 25 | line = fgetl(fid); 26 | fclose(fid); 27 | toks = tokenize(line, '='); 28 | outputnames = tokenize(toks{1}, ',[] '); 29 | for i=1:numel(outputnames) 30 | varargout{i} = S.(outputnames{i}); 31 | end 32 | 33 | end 34 | -------------------------------------------------------------------------------- /stats/crossProduct.m: -------------------------------------------------------------------------------- 1 | function out = crossProduct(varargin) 2 | %% Return the cartesian product, (all combinations) of the input lists 3 | % out = crossProduct(A, B, C, ...) each row of outcontain all combinations 4 | % of A, B, C, ... Example 5 | % C = crossProduct(1:2, 2:4, 3:4) 6 | % 1 2 3 7 | % 2 2 3 8 | % 1 3 3 9 | % 2 3 3 10 | % 1 4 3 11 | % 2 4 3 12 | % 1 2 4 13 | % 2 2 4 14 | % 1 3 4 15 | % 2 3 4 16 | % 1 4 4 17 | % 2 4 4 18 | 19 | % This file is from matlabtools.googlecode.com 20 | 21 | 22 | out = gridSpace(varargin{:}); % works for any number of dimensions. 23 | %{ 24 | switch nargin 25 | case 2 26 | [C1, C2] = meshgrid(A, B); 27 | out = [C1(:) C2(:)]; 28 | case 3 29 | [C1, C2, C3] = ndgrid(A, B,C ); 30 | out = [C1(:) C2(:) C3(:)]; 31 | otherwise 32 | error('not supported') 33 | end 34 | 35 | end 36 | %} 37 | 38 | end 39 | -------------------------------------------------------------------------------- /util/SetDefaultValue.m: -------------------------------------------------------------------------------- 1 | function SetDefaultValue(position, argName, defaultValue) 2 | % Initialize a missing or empty value in the caller function 3 | % 4 | % SETDEFAULTVALUE(POSITION, ARGNAME, DEFAULTVALUE) checks to see if the 5 | % argument named ARGNAME in position POSITION of the caller function is 6 | % missing or empty, and if so, assigns it the value DEFAULTVALUE. 7 | % 8 | % Example: 9 | % function x = TheCaller(x) 10 | % SetDefaultValue(1, 'x', 10); 11 | % end 12 | % TheCaller() % 10 13 | % TheCaller([]) % 10 14 | % TheCaller(99) % 99 15 | % 16 | % $Author: Richie Cotton $ $Date: 2010/03/23 $ 17 | %PMTKauthor Richie Cotton 18 | %PMTKurl http://www.mathworks.com/matlabcentral/fileexchange/27056-set-default-values 19 | %PMTKdate March 23, 2010 20 | 21 | % This file is from matlabtools.googlecode.com 22 | 23 | if evalin('caller', 'nargin') < position || ... 24 | isempty(evalin('caller', argName)) 25 | assignin('caller', argName, defaultValue); 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /util/protect.m: -------------------------------------------------------------------------------- 1 | function func = protect(varargin) 2 | % Wrap a function handle guarding against a specific value, e.g. [] 3 | % Takes in a function handle and returns a protected version that when 4 | % executed, returns the default value whenever guard(input) is true and 5 | % otherwise evaluates normally. The default guard is @isempty and the 6 | % default value is 0. 7 | 8 | % This file is from matlabtools.googlecode.com 9 | 10 | 11 | 12 | % Example: 13 | % cellfun(@mean,{ {}, 1:10, 2:20, 3:30, {} }; % this will fail because of the empty cells 14 | % cellfun(protect(@mean),{ {}, 1:10, 2:20, 3:30, {} }) 15 | % ans = 16 | % 0 5.5000 11.0000 16.5000 0 17 | 18 | [fn,default,guard] = process_options(varargin,'*func',@(x)x,'default',0,'guard',@isempty); 19 | function out = wrapper(in) 20 | if guard(in) 21 | out = default; 22 | else 23 | out = fn(in); 24 | end 25 | end 26 | func = @wrapper; 27 | end 28 | 29 | 30 | -------------------------------------------------------------------------------- /stats/polyBasis.m: -------------------------------------------------------------------------------- 1 | function [X, mu, sigma2] = polyBasis(x, d, mu, sigma2) 2 | %% Polynomial basis expansion of degree d 3 | % function [X] = polyBasis(x, d) 4 | % x(i) -> [1 x(i) x(i)^2 ... x(i)^d] stored in rows of X 5 | % We put highest powers first, to be consistent with Matlab's convention (see polyfit) 6 | % 7 | % function [X, mu, sigma2] = polyBasis(x, d) 8 | % We standardize x first, and return the mean and variance 9 | % 10 | % function [X] = polyBasis(x, d, mu, sigma2) 11 | % We standardize x first using specified mean and variance 12 | 13 | % This file is from matlabtools.googlecode.com 14 | 15 | 16 | x = x(:); 17 | if nargout > 1 18 | [x, mu, sigma2] = standardize(x); 19 | elseif nargin > 2 20 | [x] = standardize(x, mu, sigma2); 21 | end 22 | n = size(x,1); 23 | X(:,1) = ones(n,1,class(x)); 24 | for j = 2:d+1 25 | X(:,j) = x.*X(:,j-1); 26 | end 27 | 28 | if 0 29 | X(:,d+1) = ones(n,1,class(x)); 30 | for j = d:-1:1 31 | X(:,j) = x.*X(:,j+1); 32 | end 33 | end 34 | 35 | end 36 | -------------------------------------------------------------------------------- /metaTools/writeText.m: -------------------------------------------------------------------------------- 1 | function writeText(text, fname, append) 2 | % Write text to a file. 3 | % 4 | % WARNING: Any existing text inside fname will be lost unless in append 5 | % mode. 6 | % 7 | % INPUTS: 8 | % 9 | % text - an N-by-1 cell array of strings written out as N separate lines. 10 | % fname - the name of the output file. 11 | % append - (default=false) if true, the text is appended to the end of the 12 | % file or added to a new file if it doesn't exist. If false, the file, if 13 | % it exists, is completely overwritten by the new text. 14 | % 15 | %% 16 | 17 | % This file is from matlabtools.googlecode.com 18 | 19 | if ischar(text) 20 | text = mat2cellRows(text); 21 | end 22 | 23 | if nargin < 3, append = false;end 24 | 25 | if append 26 | fid = fopen(fname,'a'); 27 | else 28 | fid = fopen(fname,'w+'); 29 | end 30 | if fid < 0 31 | error('could not open %s',fname); 32 | end 33 | for i=1:numel(text) 34 | fprintf(fid,'%s\n',text{i}); 35 | end 36 | fclose(fid); 37 | 38 | end 39 | -------------------------------------------------------------------------------- /stats/multiSigmoid.m: -------------------------------------------------------------------------------- 1 | function [P] = multiSigmoid(X, w) 2 | % Softmax function 3 | %#eml 4 | % X is n*d 5 | % w is d*(C-1) last column is all 0s 6 | % P is n*C 7 | % 8 | % Based on code by Balaji Krishnapuram 9 | 10 | % This file is from matlabtools.googlecode.com 11 | 12 | 13 | [N,d]=size(X); %X->Nxd 14 | W=reshape(w,d,[]); 15 | 16 | M=size(W,2)+1; % M = nclasses 17 | 18 | % Activation for the sigmoids: 19 | a=[X*W zeros(N,1)]; %a->N*(M) 20 | 21 | % Ensure that sum(exp(a), 2) does not overflow 22 | maxcut = log(realmax) - log(M); 23 | a = min(a, maxcut); 24 | 25 | % Ensure that exp(a) > 0 26 | mincut = log(realmin); 27 | a = max(a, mincut); 28 | 29 | % Compute the Probabilities: 30 | temp = exp(a); 31 | P = temp./(sum(temp, 2)*ones(1,M)); 32 | 33 | % Ensure that log(P) is computable 34 | %P(P tags 3 | % If any %s', t{www(i)}, name); 24 | end 25 | http = find(cellfun(@(c)startswith(c, 'http://'), t)); 26 | for i=1:numel(http) 27 | if nargin < 2, name = t{http(i)}; end 28 | t{http(i)} = sprintf('%s', t{http(i)}, name); 29 | end 30 | 31 | ismodified = ~isempty(http) || ~isempty(www); 32 | 33 | text = catString(t, ' '); 34 | 35 | end 36 | -------------------------------------------------------------------------------- /stats/computeCounts.m: -------------------------------------------------------------------------------- 1 | function count = computeCounts(X, sz) 2 | % Count the number of times each combination of discrete assignments occurs 3 | % data is ncases-by-nvars 4 | % sz(i) : values for variable i are assumed to be in [1:sz(i)] 5 | % 6 | % Example: to compute a 2x2 contingency table on binary data 7 | % use C = computeCounts([X(:) Y(:)]+1, [2 2]); 8 | %% 9 | 10 | % This file is from matlabtools.googlecode.com 11 | 12 | assert(length(sz) == size(X, 2)); 13 | P = prod(sz); 14 | indices = subv2ind(sz, X); 15 | count = histc(indices, 1:P); 16 | count = reshapePMTK(count, sz); 17 | 18 | % test on contingency table 19 | if 0 20 | X = [0 1 0 0]; Y = [0 1 1 1]; data = [X(:) Y(:)]; 21 | C = computeCounts(data+1, [2 2]); 22 | N00 = 0; N01 = 0; N10 = 0; N11 = 0; 23 | for i=1:length(X) 24 | if X(i)==0 & Y(i)==0, N00 = N00 + 1; end 25 | if X(i)==0 & Y(i)==1, N01 = N01 + 1; end 26 | if X(i)==1 & Y(i)==0, N10 = N10 + 1; end 27 | if X(i)==1 & Y(i)==1, N11 = N11 + 1; end 28 | end 29 | assert(N00==C(1,1)); assert(N01==C(1,2)); 30 | assert(N10==C(2,1)); assert(N11==C(2,2)); 31 | end 32 | 33 | end 34 | 35 | -------------------------------------------------------------------------------- /metaTools/multiLineString.m: -------------------------------------------------------------------------------- 1 | function S = multiLineString(varargin) 2 | %% Parses the multiline comment just below where it is called 3 | % 4 | % 5 | % 6 | %% Example 7 | % 8 | % 9 | % function foo 10 | % 11 | % S = multiLineString('test', 3); 12 | % %{ 13 | % The text here will be converted to a string using sprintf like syntax 14 | % so that this %s is converted to 'test' and this %d is converted to 3. 15 | % New lines are inserted for every new line of this comment, and the 16 | % multiline string ends when I end the block comment. 17 | % 18 | % %} 19 | % 20 | % S now stores the text above with the '%' leading symbols removed. 21 | % 22 | % 23 | % 24 | %% 25 | 26 | % This file is from matlabtools.googlecode.com 27 | 28 | 29 | stack = dbstack('-completenames'); 30 | if numel(stack) < 2 31 | error('This function cannot be called from the command prompt'); 32 | end 33 | T = getText(stack(2).file); 34 | T = T((stack(2).line):end); 35 | 36 | start = cellfind(T, '%{', 1, 'first'); 37 | endl = cellfind(T, '%}', 1, 'first'); 38 | T = strtrim(T(start+1:endl-1)); 39 | S = sprintf(catString(T, '\n'), varargin{:}); 40 | end 41 | -------------------------------------------------------------------------------- /stats/mkStochastic.m: -------------------------------------------------------------------------------- 1 | function [T,Z] = mkStochastic(T) 2 | % Make a multidimensional array sum to one along its last dimension 3 | % [T,Z] = mk_stochastic(T) 4 | % 5 | % If T is a vector, it will sum to 1. 6 | % If T is a matrix, each row will sum to 1. 7 | % If T is a 3D array, then sum_k T(i,j,k) = 1 for all i,j. 8 | 9 | % This file is from matlabtools.googlecode.com 10 | 11 | 12 | % Set zeros to 1 before dividing 13 | % This is valid since S(j) = 0 iff T(i,j) = 0 for all j 14 | 15 | if isvector(T) 16 | [T, Z] = normalize(T); 17 | else 18 | [T, Z] = normalize(T, ndims(T)); 19 | end 20 | 21 | 22 | % if (ndims(T)==2) & (size(T,1)==1 | size(T,2)==1) % isvector 23 | % [T,Z] = normalize(T); 24 | % elseif ndims(T)==2 % matrix 25 | % Z = sum(T,2); 26 | % S = Z + (Z==0); 27 | % norm = repmat(S, 1, size(T,2)); 28 | % T = T ./ norm; 29 | % else % multi-dimensional array 30 | % ns = size(T); 31 | % T = reshape(T, prod(ns(1:end-1)), ns(end)); 32 | % Z = sum(T,2); 33 | % S = Z + (Z==0); 34 | % norm = repmat(S, 1, ns(end)); 35 | % T = T ./ norm; 36 | % T = reshape(T, ns); 37 | % end 38 | 39 | end 40 | -------------------------------------------------------------------------------- /stats/subsets1.m: -------------------------------------------------------------------------------- 1 | function sub_s=subsets1(s, k) 2 | % Creates sub-sets of a specific size from a given set 3 | % SS = subsets1(S, k) 4 | % 5 | % S is the given set 6 | % k is the required sub-sets size 7 | % 8 | % Example: 9 | % 10 | % >> ss=subsets1([1:4],3); 11 | % >> ss{:} 12 | % ans = 13 | % 1 2 3 14 | % ans = 15 | % 1 2 4 16 | % ans = 17 | % 1 3 4 18 | % ans = 19 | % 2 3 4 20 | % 21 | %PMTKauthor Raanan Yehezkel 22 | %PMTKdate 2004 23 | 24 | % This file is from matlabtools.googlecode.com 25 | 26 | 27 | if k<0 % special case 28 | error('subset size must be positive'); 29 | elseif k==0 % special case 30 | sub_s={[]}; 31 | else 32 | l=length(s); 33 | ss={}; 34 | if l>=k 35 | if k==1 % Exit condition 36 | for I=1:l 37 | ss{I}=s(I); 38 | end 39 | else 40 | for I=1:l 41 | ss1=subsets1(s([(I+1):l]),k-1); 42 | for J=1:length(ss1) 43 | ss{end+1}=[s(I),ss1{J}]; 44 | end 45 | end 46 | end 47 | end 48 | sub_s=ss; 49 | end 50 | end 51 | 52 | -------------------------------------------------------------------------------- /graphics/plotPatches.m: -------------------------------------------------------------------------------- 1 | function plotPatches( A, cols) 2 | % display receptive field(s) or basis vector(s) for image patches 3 | % 4 | % A(:,i) is i'th patch, assumed to be square 5 | % cols number of columns (x-dimension of grid) 6 | 7 | if nargin < 2 8 | [nr nc] = nsubplots(size(A,2)); 9 | cols = nc; 10 | end 11 | 12 | %PMTKauthor Aaop Hyvarinen 13 | 14 | %set colormap 15 | colormap(gray(256)); 16 | 17 | %normalize each patch 18 | A=A./(ones(size(A,1),1)*max(abs(A))); 19 | 20 | % This is the side of the window 21 | dim = sqrt(size(A,1)); 22 | 23 | % Helpful quantities 24 | dimp = dim+1; 25 | rows = floor(size(A,2)/cols); %take floor just in case cols is badly specified 26 | 27 | % Initialization of the image 28 | I = ones(dim*rows+rows-1,dim*cols+cols-1); 29 | 30 | %Transfer features to this image matrix 31 | for i=0:rows-1 32 | for j=0:cols-1 33 | % This sets the patch 34 | I(i*dimp+1:i*dimp+dim,j*dimp+1:j*dimp+dim) = ... 35 | reshape(A(:,i*cols+j+1),[dim dim]); 36 | end 37 | end 38 | 39 | %Save of plot results 40 | imagesc(I); 41 | axis equal 42 | axis off 43 | %print('-dps',[figurepath,filename,'.eps']) 44 | 45 | end 46 | -------------------------------------------------------------------------------- /graph/mkChordal.m: -------------------------------------------------------------------------------- 1 | function [G, fill_ins] = mkChordal(G, order) 2 | % Eliminate nodes in specified order, and ensure uneliminated 3 | % neighbors are fully connected by adding edges if necessary 4 | % 5 | % fill_ins(i,j) = 1 iff we add a fill-in arc between i and j. 6 | % PMTKmodified Matt Dunham 7 | 8 | % This file is from matlabtools.googlecode.com 9 | 10 | 11 | MG = G; 12 | n = length(G); 13 | eliminated = false(1, n); 14 | for i=1:n 15 | G = setdiag(G, 0); 16 | u = order(i); 17 | nodes = false(1, n); 18 | nodes([find(G(u, :)) find(G(:, u))']) = true; 19 | nodes = nodes & ~eliminated; 20 | nodes(u) = true; 21 | G(nodes, nodes) = 1; 22 | eliminated(u) = true; 23 | 24 | %U = find(~eliminated); % uneliminated 25 | %nodes = intersectPMTK(neighbors(G, u), U); % look up neighbors in the partially filled-in graph 26 | %nodes = unionPMTK(nodes, u); % the clique will always contain at least u 27 | %G(nodes, nodes) = 1; % make them all connected to each other 28 | %G = setdiag(G, 0); 29 | %eliminated(u) = true; 30 | end 31 | if nargout > 1 32 | fill_ins = sparse(triu(max(0, G - MG), 1)); 33 | end 34 | end 35 | 36 | -------------------------------------------------------------------------------- /stats/dblquadvec.m: -------------------------------------------------------------------------------- 1 | function q = dblquadvec(f, varargin) 2 | % Calls dblquadvec but assumes you can't vectorize your input function 3 | % DBLQUADVEC has the same calling syntax as DBLQUAD but doesn't require that 4 | % the integrand be vectorized. 5 | % 6 | % Q = DBLQUADVEC(FUN,A,B) tries to approximate the integral of scalar-valued 7 | % function FUN from A to B to within an error of 1.e-6 using recursive 8 | % adaptive Simpson quadrature. FUN is a function handle. 9 | % 10 | % See also 11 | % DBLQUAD 12 | % 13 | %PMTKauthor Aki Vehtari 14 | %PMTKurl http://www.lce.hut.fi/teaching/S-114.2601/ex/dblquadvec.m 15 | 16 | % This file is from matlabtools.googlecode.com 17 | 18 | 19 | % Based on quadvec by Loren Shure 20 | % http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=10667&objectType=file 21 | 22 | q = dblquad(@g, varargin{:}); % like quadl, but supplies g as the argument 23 | function y = g(A,B,varargin) % make f into a "vectorized" function 24 | y = zeros(size(A)); 25 | for i = 1:numel(A) 26 | y(i) = f(A(i),B,varargin{:}); % this f refers to the argument of quadvec 27 | end 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /stats/minK.m: -------------------------------------------------------------------------------- 1 | function [val,idx] = minK(A,k) 2 | %% Efficiently return the K smallest elements along the 2nd dimension 3 | % Just like built in min except we return the k smallest along the 2nd 4 | % dimension so that if A is m-by-n val is m-by-k. 5 | % 6 | % 7 | % Sorting requires O(nlog(n)) time, whereas calling min k times requires 8 | % O(n*k) time. Therefore we pick the appropriate method based on relative 9 | % size of k and log(n). 10 | 11 | % This file is from matlabtools.googlecode.com 12 | 13 | 14 | sz = size(A); 15 | if(sz(2) == 1) 16 | A = A'; 17 | sz = size(A); 18 | end 19 | if(k > sz(2)) 20 | error('k must be smaller than or equal to size(A,2)'); 21 | end 22 | 23 | if log(sz(2)) < k % sort the whole thing and throw away what we don't need 24 | [val,idx] = sort(A,2); 25 | val = val(:,1:k); 26 | idx = idx(:,1:k); 27 | else % loop and call min each time 28 | val = zeros(size(A,1),k); 29 | idx = zeros(size(A,1),k); 30 | for i=1:k 31 | [val(:,i),idx(:,i)] = min(A,[],2); 32 | A(sub2ind(sz,(1:sz(1))',idx(:,i))) = inf; % mark the value(s) we just found 33 | end 34 | end 35 | 36 | 37 | 38 | end 39 | -------------------------------------------------------------------------------- /util/nunique.m: -------------------------------------------------------------------------------- 1 | function N = nunique(X, dim) 2 | % Efficiently count the unique elements of X along the specified dimension 3 | % Like length(unique(X(:, j)) or length(unique(X(i, :)) but vectorized. 4 | % Supports multidimensional arrays, e.g. nunique(X, 3). 5 | % 6 | % 7 | % Example: 8 | %X = 9 | % 5 4 3 3 2 1 4 10 | % 2 1 1 1 1 4 3 11 | % 3 1 4 2 3 4 1 12 | % 2 4 1 1 5 3 1 13 | % 4 5 1 5 1 5 3 14 | % 2 5 4 1 2 2 4 15 | % 2 4 3 3 3 1 4 16 | % 4 1 2 3 1 2 4 17 | % 18 | % 19 | % nunique(X, 1) 20 | % ans = 21 | % 4 3 4 4 4 5 3 22 | % 23 | % 24 | % 25 | % nunique(X, 2) 26 | % ans = 27 | % 5 28 | % 4 29 | % 4 30 | % 5 31 | % 4 32 | % 4 33 | % 4 34 | % 4 35 | 36 | % This file is from matlabtools.googlecode.com 37 | 38 | 39 | if nargin == 1 40 | dim = find(size(X)~=1, 1); 41 | if isempty(dim), dim = 1; end 42 | end 43 | N = sum(diff(sort(X, dim), [], dim) > 0, dim) + 1; 44 | 45 | end 46 | -------------------------------------------------------------------------------- /util/structvals.m: -------------------------------------------------------------------------------- 1 | function varargout = structvals(S, varargin) 2 | % Extract the values of a structure into an output argument list 3 | % specify a cell array listing the fieldnames in the order you want them 4 | % returned. The number of output arguments must equal the number of names 5 | % in order. 6 | % 7 | % Example 8 | % 9 | % model.mu = zeros(1, 5) 10 | % model.Sigma = 2*eye(5) 11 | % model.dof = 5 12 | % [mu, Sigma, dof] = structvals(model, {'mu', 'Sigma', 'dof'}) 13 | 14 | % This file is from matlabtools.googlecode.com 15 | 16 | if nargin < 2 17 | error('You must specify which fields you want to extract'); 18 | end 19 | if iscell(varargin{1}) 20 | order = varargin{1}; 21 | else 22 | order = varargin; 23 | end 24 | if nargout ~= numel(order) 25 | error('The number of output args must equal the number of specified field names'); 26 | end 27 | assert(nargout == numel(order)); 28 | for i=1:numel(order) 29 | if ~isfield(S, order{i}) 30 | error('%s is not a field of this struct', order{i}); 31 | end 32 | end 33 | order = rowvec(order); 34 | order = [order, rowvec(setdiff(fieldnames(S), order))]; 35 | varargout = struct2cell(orderfields(S, order)); 36 | 37 | end 38 | -------------------------------------------------------------------------------- /graph/mkGrid.m: -------------------------------------------------------------------------------- 1 | function G = mkGrid(M, N, doPlot) 2 | %% Create an M by N undirected grid as an adjacency matrix in column order 3 | % i.e. mkGrid(3, 5) creates a grid that looks like this: 4 | % 5 | % 1-4-7-10-13 6 | % | | | | | 7 | % 2-5-8-11-14 8 | % | | | | | 9 | % 3-6-9-12-15 10 | % 11 | % Suggested drawNetwork layout: Matrixlayout(M, N) as in 12 | % drawNetwork(G, '-undirected', true, '-layout', Matrixlayout(M, N)); 13 | %% 14 | 15 | % This file is from matlabtools.googlecode.com 16 | 17 | if nargin < 1 18 | N = 5; 19 | end 20 | if nargin < 2 21 | M = N; 22 | end 23 | 24 | if nargin < 3 25 | doPlot = false; 26 | end 27 | 28 | helper = zeros(M, N); 29 | helper(:) = 1:N*M; 30 | ne = (N-1)*M + (M-1)*N; 31 | G = sparse([], [], [], N*M, N*M, ne); 32 | 33 | for i=1:M 34 | row = helper(i, :) ; 35 | for k=2:N 36 | G(row(k-1), row(k)) = 1; 37 | end 38 | end 39 | 40 | for j = 1:N 41 | col = helper(:, j); 42 | for k=2:M 43 | G(col(k-1), col(k)) = 1; 44 | end 45 | end 46 | G = mkSymmetric(G); 47 | G = setdiag(G, 0); 48 | 49 | if doPlot && ~isOctave() 50 | drawNetwork(G, '-undirected', true, '-layout', Matrixlayout(M, N)); 51 | end 52 | end 53 | -------------------------------------------------------------------------------- /oop/getClasses.m: -------------------------------------------------------------------------------- 1 | function classes = getClasses(varargin) 2 | % Get a list of all of the classes below the specified directory 3 | % that are on the Matlab path. You can optionally specify directories to 4 | % ignore. By default, the util and unitTests directories are ignored. 5 | % PMTKneedsMatlab 2008 6 | 7 | % This file is from matlabtools.googlecode.com 8 | 9 | 10 | [source,ignoreDirs,topOnly] = process_options(varargin,'source',pwd(),'ignoreDirs',{},'topOnly',false); 11 | 12 | if nargin < 1, source = '.'; end 13 | if nargin < 2, 14 | if nargin < 3, ignoreDirs = {}; end 15 | if exist('PMTKroot.m','file') 16 | if ~strcmpi(source,fullfile(PMTKroot(),'util')) 17 | ignoreDirs = [ignoreDirs;fullfile(PMTKroot(),'util')]; 18 | end 19 | if ~strcmpi(source,fullfile(PMTKroot(),'unitTests')) 20 | ignoreDirs = [ignoreDirs;fullfile(PMTKroot(),'unitTests')]; 21 | end 22 | end 23 | end 24 | 25 | classes = filterCell(cellfuncell(@(c)c(1:end-2),mfiles(source,topOnly)),@(m)isclassdef(m)); 26 | for i=1:numel(ignoreDirs) 27 | classes = setdiff(classes, filterCell(cellfuncell(@(c)c(1:end-2),mfiles(ignoreDirs{i})),@(m)isclassdef(m))); 28 | end 29 | 30 | end 31 | -------------------------------------------------------------------------------- /stats/partitionedMean.m: -------------------------------------------------------------------------------- 1 | function [M, counts] = partitionedMean(X, y, C) 2 | % Group the rows of X according to the class labels in y and take the mean of each group 3 | % 4 | % X - an n-by-d matrix of doubles 5 | % y - an n-by-1 vector of ints in 1:C 6 | % C - (optional) the number of classes, (calculated if not specified) 7 | % 8 | % M - a C-by-d matrix of means. 9 | % counts(i) = sum(y==i) 10 | % 11 | % See also partitionedSum 12 | 13 | % This file is from matlabtools.googlecode.com 14 | 15 | 16 | if nargin < 3 17 | C = nunique(y); 18 | end 19 | if 1 20 | d = size(X,2); 21 | M = zeros(C, d); 22 | for c=1:C 23 | ndx = (y==c); 24 | M(c, :) = mean(X(ndx, :)); 25 | end 26 | counts = histc(y, 1:C); 27 | else 28 | % fancy vectorized version 29 | if isOctave 30 | S = bsxfun(@eq, (1:C)', y'); 31 | else 32 | S = bsxfun(@eq, sparse(1:C)', y'); % C-by-n logical sparse matrix, (basically a one-of-K encoding transposed) 33 | end 34 | M = S*X; % computes the sum, yielding a C-by-d matrix 35 | counts = histc(y, 1:C); 36 | M = bsxfun(@rdivide, M, counts); % divide by counts to get mean 37 | end 38 | 39 | end 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /metaTools/compileC.m: -------------------------------------------------------------------------------- 1 | function compileC(root, excludedNames) 2 | % Try and compile all mexable c-files in the directory structure that 3 | % have not already been compiled. 4 | % 5 | % excludedNames is a cell array of strings. A file is excluded if it 6 | % contains one of these strings in its absolute path name, thus it can be 7 | % the name of a file, directory, or parent directory. 8 | %% 9 | % PMTKneedsMatlab 10 | %% 11 | 12 | % This file is from matlabtools.googlecode.com 13 | 14 | if nargin < 1, root = pmtk3Root(); end 15 | 16 | if nargin < 2 17 | excludedNames = {'external' % most external packages require custom mex linking 18 | }; 19 | end 20 | cfiles = cfilelist(root); 21 | for i=1:numel(excludedNames) 22 | ex = cellfun(@(c)isSubstring(excludedNames{i}, c), cfiles); 23 | cfiles(ex) = []; 24 | end 25 | 26 | for j=1:numel(cfiles) 27 | try 28 | cfile = cfiles{j}; 29 | fname = fnameOnly(cfile); 30 | if ~(exist(fname, 'file') == 3) 31 | cd(fileparts(cfile)); 32 | fprintf('Compiling %s\n',cfile); 33 | mex(cfile); 34 | end 35 | catch ME 36 | fprintf('Could not compile %s\n', cfile); 37 | end 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /graphics/pdfcrop.m: -------------------------------------------------------------------------------- 1 | function pdfcrop(h,hborder,vborder) 2 | %Make the paper size, the same as the figure size, (plus an optional 3 | %border). This is important when exporting figures to pdf for inclusion in 4 | %latex for example. 5 | % 6 | %h is the handle to the current figure and is returned by the matlab figure 7 | %command as in 'h = figure;' when a new figure is created, or by the 'gcf' 8 | %command, which returns the current figure. If it is not specified, h is 9 | %set to the current figure. You can also specify an optional white border 10 | %in inches by specifying values for the horizontal border, hborder, and the 11 | %vertical border, vborder). 12 | % 13 | %'hborder' The horizontal border, (default = 0.1 inches) 14 | %'vborder' the vertical border, (default = 0.1 inches) 15 | % 16 | %% 17 | 18 | % This file is from matlabtools.googlecode.com 19 | 20 | 21 | if(nargin <= 1) 22 | hborder = 0.1; vborder = 0.1; 23 | end 24 | if(nargin == 0);h = gcf;end 25 | if ~ishandle(h); return; end 26 | set(h,'Units','inches'); 27 | pos = get(h,'Position'); 28 | width = pos(3) + hborder; 29 | height = pos(4) + vborder; 30 | set(h,'PaperSize',[width,height]); 31 | set(h,'PaperPositionMode','auto'); 32 | 33 | end 34 | -------------------------------------------------------------------------------- /metaTools/googleCodeLink.m: -------------------------------------------------------------------------------- 1 | function link = googleCodeLink(fname, displayName, type) 2 | %% Return the html link to fname on a PMTK associated google code repository 3 | % 4 | %% 5 | 6 | % This file is from matlabtools.googlecode.com 7 | 8 | if nargin < 3 9 | type = 'html'; 10 | end 11 | 12 | fname = which(fname); 13 | if nargin < 2 14 | displayName = fnameOnly(fname); 15 | end 16 | if startswith(fname, pmtk3Root()) 17 | googleRoot = 'http://pmtk3.googlecode.com/svn/trunk'; 18 | root = pmtk3Root(); 19 | elseif startswith(fname, pmtkSupportRoot()) 20 | googleRoot = 'http://pmtksupport.googlecode.com/svn/trunk'; 21 | root = pmtkSupportRoot(); 22 | elseif exist('matlabToolsRoot', 'file') && startswith(fname, matlabToolsRoot()) 23 | googleRoot = 'http://matlabtools.googlecode.com/svn/trunk'; 24 | root = matlabToolsRoot(); 25 | else 26 | link = ''; 27 | return; 28 | end 29 | link = [googleRoot, strrep(fname(length(root)+1:end), '\', '/')]; 30 | switch type 31 | case 'html' 32 | link = sprintf('%s',link, displayName); 33 | case 'publish' 34 | link = sprintf('<%s %s>',link, displayName); 35 | case 'wiki' 36 | link = sprintf('[%s %s]',link, displayName); 37 | end 38 | 39 | -------------------------------------------------------------------------------- /stats/polyDataMake.m: -------------------------------------------------------------------------------- 1 | function [xtrain, ytrain, xtest, ytestNoisefree, ytestNoisy, sigma2] = polyDataMake(varargin) 2 | %% Sample Data 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | [sampling, deg, n] = process_options(varargin, ... 7 | 'sampling', 'sparse', 'deg', 3, 'n', 21); 8 | setSeed(0); 9 | switch sampling 10 | case 'irregular', xtrain = [-1:0.1:-0.5, 3:0.1:3.5]'; 11 | case 'sparse', xtrain = [-3, -2, 0, 2, 3]'; 12 | case 'dense', xtrain = [-5:0.6:5]'; %[-5:0.4:5]'; 13 | case 'thibaux', xtrain = linspace(0,20,n)'; 14 | end 15 | if strcmp(sampling, 'thibaux') 16 | randn('state', 654321); 17 | xtest = [0:0.1:20]'; 18 | sigma2 = 4; 19 | w = [-1.5; 1/9]; 20 | fun = @(x) w(1)*x + w(2)*x.^2; 21 | else 22 | %xtest = [-5:0.1:5]'; 23 | xtest = [-7:0.1:7]'; 24 | if deg==2 25 | fun = @(x) (10 + x + x.^2); 26 | elseif deg==3 27 | fun = @(x) (10 + x + x.^3); 28 | else 29 | error(['bad degree, dude ' deg]) 30 | end 31 | %sigma2 = 1^2; 32 | sigma2 = 5^2; 33 | end 34 | ytrain = feval(fun, xtrain) + randn(size(xtrain,1),1)*sqrt(sigma2); 35 | ytestNoisefree = feval(fun, xtest); 36 | ytestNoisy = ytestNoisefree + randn(size(xtest,1),1)*sqrt(sigma2); 37 | restoreSeed; 38 | 39 | 40 | -------------------------------------------------------------------------------- /graphics/pmtkColors.m: -------------------------------------------------------------------------------- 1 | function [colors, colorMap] = pmtkColors() 2 | 3 | % http://www.mathworks.com/access/helpdesk/help/techdoc/ref/colorspec.html 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | lightblue = [55 155 255] / 255; 9 | orange = [255 128 0 ] / 255; 10 | green = [0 255 64 ] / 255; 11 | magenta = [255 0 128 ] / 255; 12 | green2 = [132 199 71 ] / 255; 13 | cyan = [61 220 176 ] / 255; 14 | yellow2 = [215 215 0 ] / 255; 15 | yellow = [255 25 0 ] / 255; 16 | brown = [128 64 0 ] / 255; 17 | blue = [0 0 255 ] / 255; 18 | red = [255 0 0 ] / 255; 19 | black = [0 0 0 ] / 255; 20 | gray = [128 128 128 ] / 255; 21 | 22 | colors = { lightblue, orange, green, magenta, yellow, cyan, ... 23 | brown, blue, green2, red, gray, black}; 24 | colors = repmat(colors, 1, length(colors)); 25 | 26 | colorMap.lightblue = lightblue; 27 | colorMap.orange = orange; 28 | colorMap.green = green; 29 | colorMap.cyan = cyan; 30 | colorMap.yellow = yellow; 31 | colorMap.magenta = magenta; 32 | colorMap.green2 = green2; 33 | colorMap.brown = brown; 34 | colorMap.blue = blue; 35 | end 36 | -------------------------------------------------------------------------------- /metaTools/isEndKeywordMissing.m: -------------------------------------------------------------------------------- 1 | function answer = isEndKeywordMissing(fname) 2 | % Return true if the syntactically optional end keyword is missing 3 | % from the end of the function. 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | if ~isfunction(fname) 9 | answer = false; 10 | return 11 | end 12 | text = removeComments(getText(fname)); 13 | text = cellfuncell(@removeStrings, text); 14 | text = cellfuncell(@removeTrailingComment, text); 15 | answer = countEnds(text) ~= countKeywords(text); 16 | 17 | end 18 | 19 | function n = countEnds(c) 20 | 21 | rowCount = @(s)numel(intersect({'end'}, tokenize(strtrim(s), ' ;,'))); 22 | n = sum(cellfun(rowCount, c)); 23 | end 24 | 25 | function n = countKeywords(c) 26 | 27 | keywords = {'function', 'if', 'if~', 'switch', 'for', 'while', 'try'}; 28 | rowCount = @(s)numel(intersect(keywords, tokenize(strtrim(s), ' ;,=()'))); 29 | n = sum(cellfun(rowCount, c)); 30 | 31 | end 32 | 33 | function s = removeTrailingComment(s) 34 | toks = tokenize(s, '%'); 35 | s = toks{1}; 36 | end 37 | 38 | function s = removeStrings(s) 39 | ndx = find(s==''''); 40 | j = 1; 41 | remove = []; 42 | while j < numel(ndx) 43 | remove = [remove, ndx(j):ndx(j+1)]; %#ok 44 | j = j+2; 45 | end 46 | s(remove) = ''''; 47 | end 48 | -------------------------------------------------------------------------------- /util/extractArgs.m: -------------------------------------------------------------------------------- 1 | function varargout = extractArgs(indices,args) 2 | % Extract specified arguments / values from the output of processArgs 3 | % also returning the unused name/value pairs in a cell array. 4 | % 5 | % When processArgs is called with exactly one output, the output contains 6 | % all of the name value pairs in a single cell array. The values are either 7 | % the programmer specified defaults, or if specified, the user values. 8 | % 9 | % This function returns the requested arg values in the order they were 10 | % requested, (not the corresponding names). However, the unused name value 11 | % pairs are returned as the last output argument, bundled in a cell array. 12 | % This can be then be passed to another function. 13 | % 14 | % Example: 15 | % 16 | % function [beta,delta,epsilon] = outerFunction(varargin) 17 | % args = processArgs(varargin,'-alpha',1,'-beta',2,'-gamma',3,'-delta',4) 18 | % [beta,delta,unused] = extractArgs([2,4],args); 19 | % epsilon = anotherFunction(unused{:}); 20 | % end 21 | 22 | % This file is from matlabtools.googlecode.com 23 | 24 | 25 | 26 | valIDX = 2:2:numel(args); 27 | nameIDX = 1:2:numel(args); 28 | vals = args(valIDX(indices)); 29 | args(union(valIDX(indices),nameIDX(indices))) = []; 30 | varargout = [vals,{args}]; 31 | 32 | 33 | end 34 | -------------------------------------------------------------------------------- /stats/numericalIntegral.m: -------------------------------------------------------------------------------- 1 | function val = numericalIntegral(f, range, tol) 2 | % Evalaute an integral using quad, dblquad or triple quad 3 | % f must be a function that takes an n*1, n*2 or n*3 matrix 4 | % and returns the function value at the specified points. 5 | % range is [x1min x1max x2min x2max x3min x3max] 6 | 7 | % This file is from matlabtools.googlecode.com 8 | 9 | 10 | if nargin < 3, tol = 1e-3; end 11 | ndims = length(range)/2; 12 | switch ndims 13 | case 1, 14 | foo = @(x) f(x(:)); % quad passes in 1 row vector 15 | val = quad(foo, range(1), range(2), tol); 16 | case 2, 17 | foo = @(x1,x2) f(replicateX(x1,x2)); 18 | val = dblquad(foo, range(1), range(2), range(3), range(4), tol); 19 | case 3, 20 | foo = @(x1,x2,x3) f(replicateX(x1,x2,x3)); 21 | val = triplequad(foo, range(1), range(2), range(3), range(4), range(5), range(6), tol); 22 | otherwise 23 | error('can only handle up to 3d') 24 | end 25 | end 26 | 27 | % dblquad calls f with vectorized first argument but scalar second 28 | % Here we may all argumetns have the same shape 29 | function X = replicateX(x1, x2, x3) 30 | % X(i,:) = [x1(i) x2] or [x1(i) x2 x3] 31 | n = length(x1); 32 | x2 = x2*ones(n,1); 33 | if nargin == 3 34 | x3 = x3*ones(n,1); 35 | X = [x1(:) x2(:) x3(:)]; 36 | else 37 | X = [x1(:) x2(:)]; 38 | end 39 | end 40 | 41 | 42 | -------------------------------------------------------------------------------- /stats/ROCcurve.m: -------------------------------------------------------------------------------- 1 | function [faRate, hitRate, AUC] = ROCcurve(score, trueLabel, doPlot) 2 | % Plot a receiver operating curve 3 | % function [faRate, hitRate, AUC] = plotROCcurve(score, trueLabel, doPlot) 4 | % 5 | % score(i) = confidence in i'th detection (bigger means more confident) 6 | % trueLabel(i) = 0 if background or 1 if target 7 | % doPlot - optional (default 1) 8 | % 9 | % faRate(t) = false alarm rate at t'th threshold 10 | % hitRate(t) = detection rate at t'th threshold 11 | % AUC = area under curve 12 | 13 | % This file is from matlabtools.googlecode.com 14 | 15 | 16 | if nargin < 3, doPlot = 0; end 17 | 18 | class1 = find(trueLabel==1); 19 | class0 = find(trueLabel==0); 20 | 21 | thresh = unique(sort(score)); 22 | Nthresh = length(thresh); 23 | hitRate = zeros(1, Nthresh); 24 | faRate = zeros(1, Nthresh); 25 | for thi=1:length(thresh) 26 | th = thresh(thi); 27 | % hit rate = TP/P 28 | hitRate(thi) = sum(score(class1) >= th) / length(class1); 29 | % fa rate = FP/N 30 | faRate(thi) = sum(score(class0) >= th) / length(class0); 31 | end 32 | AUC = sum(abs(faRate(2:end) - faRate(1:end-1)) .* hitRate(2:end)); 33 | 34 | if ~doPlot, return; end 35 | 36 | plot(faRate, hitRate, '-'); 37 | e = 0.05; axis([0-e 1+e 0-e 1+e]) 38 | xlabel('false alarm rate') 39 | ylabel('hit rate') 40 | grid on 41 | title(sprintf('AUC=%5.3f', AUC)) 42 | 43 | end 44 | -------------------------------------------------------------------------------- /stats/preprocessorApplyToTrain.m: -------------------------------------------------------------------------------- 1 | function [preproc, X] = preprocessorApplyToTrain(preproc, X) 2 | % Apply Preprocessor to training data and store updated 3 | % parameters inside pp object for use at test time 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | % For backwards compatibility, we replicate the 9 | % behavior of preprocessorCreate 10 | if ~isfield(preproc, 'standardizeX'), preproc.standardizeX = false; end 11 | if ~isfield(preproc, 'rescaleX'), preproc.rescaleX = false; end 12 | if ~isfield(preproc, 'kernelFn'), preproc.kernelFn = []; end 13 | if ~isfield(preproc, 'poly'), preproc.poly = []; end 14 | if ~isfield(preproc, 'addOnes'), preproc.addOnes = false; end 15 | 16 | if preproc.standardizeX 17 | [X, preproc.Xmu] = centerCols(X); 18 | [X, preproc.Xstnd] = mkUnitVariance(X); 19 | end 20 | 21 | if preproc.rescaleX 22 | if ~isfield(preproc, 'Xscale') 23 | preproc.Xscale = [-1 1]; 24 | end 25 | X = rescaleData(X, preproc.Xscale(1), preproc.Xscale(2)); 26 | 27 | end 28 | 29 | if ~isempty(preproc.kernelFn) 30 | preproc.basis = X; 31 | X = preproc.kernelFn(X, preproc.basis); 32 | end 33 | 34 | if ~isempty(preproc.poly) 35 | assert(preproc.poly > 0); 36 | X = degexpand(X, preproc.poly, false); 37 | end 38 | 39 | if preproc.addOnes 40 | X = addOnes(X); 41 | end 42 | 43 | end 44 | -------------------------------------------------------------------------------- /graphics/rocCurve.m: -------------------------------------------------------------------------------- 1 | function [faRate, hitRate, AUC] = rocCurve(score, trueLabel, doPlot) 2 | % Plot a receiver operating curve 3 | % function [faRate, hitRate, AUC] = plotROCcurve(score, trueLabel, doPlot) 4 | % 5 | % score(i) = confidence in i'th detection (bigger means more confident) 6 | % trueLabel(i) = 0 if background or 1 if target 7 | % doPlot - optional (default 1) 8 | % 9 | % faRate(t) = false alarm rate at t'th threshold 10 | % hitRate(t) = detection rate at t'th threshold 11 | % AUC = area under curve 12 | 13 | % This file is from matlabtools.googlecode.com 14 | 15 | 16 | if nargin < 3, doPlot = 0; end 17 | 18 | class1 = find(trueLabel==1); 19 | class0 = find(trueLabel==0); 20 | 21 | thresh = unique(sort(score)); 22 | Nthresh = length(thresh); 23 | hitRate = zeros(1, Nthresh); 24 | faRate = zeros(1, Nthresh); 25 | for thi=1:length(thresh) 26 | th = thresh(thi); 27 | % hit rate = TP/P 28 | hitRate(thi) = sum(score(class1) >= th) / length(class1); 29 | % fa rate = FP/N 30 | faRate(thi) = sum(score(class0) >= th) / length(class0); 31 | end 32 | AUC = sum(abs(faRate(2:end) - faRate(1:end-1)) .* hitRate(2:end)); 33 | 34 | if ~doPlot, return; end 35 | 36 | plot(faRate, hitRate, '-'); 37 | e = 0.05; axis([0-e 1+e 0-e 1+e]) 38 | xlabel('false alarm rate') 39 | ylabel('hit rate') 40 | grid on 41 | title(sprintf('AUC=%5.3f', AUC)) 42 | 43 | end 44 | -------------------------------------------------------------------------------- /oop/islocal.m: -------------------------------------------------------------------------------- 1 | function local = islocal(varargin) 2 | % Return true iff the method is locally defined in the class 3 | % which means 4 | % 5 | % (1) the method is implemented in the class, (or at least abstractly defined so long as allowAbstract = true) 6 | % (2) the method is not the class constructor 7 | % (3) the method is public 8 | % (4) the method is not hidden 9 | % 10 | % Note, the class might be overridding the method of a super class. To 11 | % check that this is not the case, check 12 | % m = methodInfo(className,methodName) 13 | % m.isNewToBranch 14 | % 15 | % 16 | % 17 | % Inputs: 18 | % 19 | % '-methodName' vectorized w.r.t methodname, (i.e. methodname can be a cell array of strings) 20 | % '-className' 21 | % '-allowAbstract' 22 | % 23 | % 24 | % 25 | % See also, localMethods 26 | % PMTKneedsMatlab 2008 27 | 28 | % This file is from matlabtools.googlecode.com 29 | 30 | 31 | [methodName,className,allowAbstract] = process_options(varargin,'methodName','','className','','allowAbstract',false); 32 | if iscell(methodName) 33 | local = cellfun(@(mn)islocal(mn,className,allowAbstract),methodName); 34 | return; 35 | end 36 | minfo = methodInfo(className,methodName); 37 | if isempty(minfo) 38 | local = false; 39 | else 40 | local = minfo.isPublic && minfo.isLocal && ~minfo.isHidden && ~minfo.isConstructor && (~minfo.isAbstract || allowAbstract); 41 | end 42 | 43 | end 44 | -------------------------------------------------------------------------------- /stats/paracylTest.m: -------------------------------------------------------------------------------- 1 | function paracylTest() 2 | %% Compare the speed of different implementations of the paracyl function 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | z=-10:0.5:10; 7 | x=-10.5:.5:10; 8 | 9 | as = [0.01 0.75 1]; 10 | bs = ones(1,4); 11 | compare = true; 12 | if true 13 | tic 14 | outNEG = zeros(numel(as), numel(z)); 15 | for k=1:length(z) 16 | for i=1:length(as) 17 | outNEG(i, k) = minidx(.5*(z(k)-x).^2+normalExpGammaNeglogpdf(x, as(i), bs(i))); 18 | end 19 | end 20 | toc 21 | end 22 | 23 | tic 24 | outNEGFast = zeros(numel(as), numel(z)); 25 | for k=1:length(z) 26 | for i=1:length(as) 27 | outNEGFast(i, k) = minidx(.5*(z(k)-x).^2+normalExpGammaNeglogpdfFast(x, as(i), bs(i))); 28 | end 29 | end 30 | toc 31 | 32 | if compare, assert(approxeq(outNEG, outNEGFast));end 33 | 34 | 35 | 36 | end 37 | 38 | 39 | 40 | function out=normalExpGammaNeglogpdf(z,shape,scale) 41 | % gamma^2 = c = scale 42 | lambda = shape; 43 | gamma = sqrt(scale); 44 | out = zeros(1, length(z)); 45 | for k=1:length(z) 46 | out(k)=-z(k)^2/(4*gamma^2)-log(mpbdv(-2*(lambda+1/2),abs(z(k))/gamma)); 47 | end 48 | end 49 | 50 | 51 | function out=normalExpGammaNeglogpdfFast(z,shape,scale) 52 | % gamma^2 = c = scale 53 | lambda = shape; 54 | gamma = sqrt(scale); 55 | out = -z.^2/(4*gamma^2)-log(paracyl(-2*(lambda+1/2), abs(z)./gamma)); 56 | end 57 | -------------------------------------------------------------------------------- /graphics/plotCVgrid.m: -------------------------------------------------------------------------------- 1 | 2 | function p = plotCVgrid(params, mu, bestParams, params1, params2) 3 | % Plot Cross validation results in 2D 4 | 5 | % This file is from matlabtools.googlecode.com 6 | 7 | 8 | if nargin < 4 || isempty(params1) 9 | params1 = unique(params(:,1)); 10 | params2 = unique(params(:,2)); 11 | end 12 | 13 | sz = nunique(params); 14 | nrows = sz(1); 15 | ncols = sz(2); 16 | X = reshape(params(:, 1), nrows, ncols); 17 | Y = reshape(params(:, 2), nrows, ncols); 18 | Z = reshape(mu, nrows, ncols); 19 | %p = surf(X, Y, Z); 20 | %view([0, 90]); 21 | imagesc(Z); 22 | set(gca, 'ytick', 1:numel(params1), 'yticklabel', params1) 23 | set(gca, 'xtick', 1:numel(params2), 'xticklabel', params2) 24 | colorbar; 25 | xlabel('first model param'); 26 | ylabel('second model param'); 27 | ndx1 = find(bestParams(1)==params1); 28 | ndx2 = find(bestParams(2)==params2); 29 | %title(sprintf('Color Denotes Score\nVal1: %f\nVal2: %f',bestParams(1), bestParams(2))); 30 | title(sprintf('Lowest cost at col = %d, row = %d', ndx2, ndx1)); 31 | %axis tight; 32 | %box on; 33 | % warning('off','MATLAB:Axes:NegativeDataInLogAxis'); 34 | % if(isequal(logspace(log10(min(mu(:, 1))), log10(max(mu(:, 1))),nunique(mu(:, 1)))',unique(mu(:, 1)))) 35 | % set(gca,'Xscale','log'); 36 | % end 37 | % if(isequal(logspace(log10(min(mu(:, 2))), log10(max(mu(:, 2))),nunique(mu(:, 2)))',unique(mu(:, 2)))) 38 | % set(gca,'Yscale','log'); 39 | % end 40 | 41 | end 42 | 43 | 44 | -------------------------------------------------------------------------------- /graphics/image_rgb.m: -------------------------------------------------------------------------------- 1 | function image_rgb(M) 2 | % Show a matrix of integers as a color image. 3 | % This is like imagesc, except we know what the mapping is from integer to color. 4 | % If entries of M contain integers in {1,2,3,4,5}, we map 5 | % this to red/green/blue/aquamarine/black. 6 | % So if we call image_rgb on 2 different matrices, 7 | % we always know black means 5. 8 | % If we use imagesc, the mapping from color to number depends on the image. 9 | % eg M=sampleDiscrete(normalize(ones(1,5)), 10,10); image_rgb(M);colorbar 10 | 11 | % This file is from matlabtools.googlecode.com 12 | 13 | 14 | cmap = [1 0 0; % red 15 | 0 1 0; % green 16 | 0 0 1; % blue 17 | 127/255 1 212/255; % aquamarine 18 | 0 0 0]; % black 19 | image(M) 20 | set(gcf,'colormap', cmap); 21 | if max(unique(M(:))) > size(cmap,1) 22 | error(sprintf('can only support %d colors', size(cmap,1))) 23 | end 24 | 25 | if 0 26 | % make dummy handles, one per object type, for the legend 27 | str = {}; 28 | for i=1:size(cmap,1) 29 | dummy_handle(i) = line([0 0.1], [0 0.1]); 30 | set(dummy_handle(i), 'color', cmap(i,:)); 31 | set(dummy_handle(i), 'linewidth', 2); 32 | str{i} = num2str(i); 33 | end 34 | legend(dummy_handle, str, -1); 35 | end 36 | 37 | if 0 38 | [nrows ncols] = size(M); 39 | img = zeros(nrows, ncols, 3); 40 | for r=1:nrows 41 | for c=1:ncols 42 | q = M(r,c); 43 | img(r,c,q) = 1; 44 | end 45 | end 46 | image(img) 47 | end 48 | 49 | end 50 | -------------------------------------------------------------------------------- /metaTools/whoDependsOnToolbox.m: -------------------------------------------------------------------------------- 1 | function f = whoDependsOnToolbox(TB, recache) 2 | % Return a list of all user files on the path that recursively depend on a toolbox 3 | %% Input 4 | % TB - the name of a toolbox, e.g. 'stats', 'images', 'optim' 5 | % 6 | % recache - [false] if true, the whoCallsMe cache is updated 7 | %% Output 8 | % f - a list of user mfiles that depend directly or indirectly, on the 9 | % toolbox. 10 | % 11 | %% Examples 12 | % 13 | % f = whoDependsOnToolbox('stats'); 14 | % f = whoDependsOnToolbox('optim'); 15 | % f = whoDependsOnToolbox('images'); 16 | % f = whoDependsOnToolbox('bioinfo'); 17 | %% See also 18 | % deptoolbox - returns more info but is not recursive 19 | %% 20 | 21 | % This file is from matlabtools.googlecode.com 22 | 23 | if nargin < 2, recache = false; end 24 | tbdir = fullfile(matlabroot(), 'toolbox', TB); 25 | if ~exist(tbdir, 'file') 26 | error('could not find %s toolbox', TB); 27 | end 28 | [l, m, G] = whoCallsMe('whoCallsMe', 'recursive', false, 'recache', recache); 29 | usesTB = @(f)any(strncmp(tbdir, depfun(f, '-toponly', '-quiet'), length(tbdir))); 30 | try 31 | tbdep = cellfun(usesTB, m); 32 | catch ME 33 | fprintf('There was an error generating the report - try recaching...\n'); 34 | f = {}; 35 | return 36 | end 37 | G = [[G, tbdep(:)]; zeros(1, length(G)+1)]; % call graph 38 | R = expm(sparse(G)); % reachability graph 39 | f = m(R(1:end-1, end) > 0); 40 | end 41 | -------------------------------------------------------------------------------- /stats/cvEstimate.m: -------------------------------------------------------------------------------- 1 | function [mu, se] = cvEstimate(fitFn, predictFn, lossFn, X, y, Nfolds, varargin) 2 | % Cross validation estimate of expected loss 3 | % model = fitFn(Xtrain, ytrain) 4 | % yhat = predictFn(model, Xtest) 5 | % L = lossFn(yhat, ytest), should return a vector of errors 6 | % X is N*D design matrix 7 | % y is N*1 8 | % Nfolds is number of CV folds 9 | % Alternatively, you can explicitly specify the test folds 10 | % using testFolds(:,f) for the f'th fold 11 | % 12 | % mu is empirical estimate of expected loss 13 | % se is standard error of this estimate 14 | 15 | % This file is from matlabtools.googlecode.com 16 | 17 | 18 | [testFolds, randomizeOrder] = process_options(varargin, ... 19 | 'testFolds', [], 'randomizeOrder', false); 20 | 21 | N = size(X,1); 22 | if isempty(testFolds) 23 | [trainfolds, testfolds] = Kfold(N, Nfolds, randomizeOrder); 24 | else 25 | % explicitly specify the test folds 26 | [nTest nFolds] = size(testFolds); 27 | testfolds = mat2cell(testFolds, nTest, ones(nFolds,1)); 28 | trainfolds = cellfun(@(t)setdiff(1:N,t), testfolds, 'UniformOutput', false); 29 | end 30 | loss = zeros(1,N); 31 | for f=1:length(trainfolds) 32 | Xtrain = X(trainfolds{f},:); Xtest = X(testfolds{f},:); 33 | ytrain = y(trainfolds{f}); ytest = y(testfolds{f}); 34 | model = fitFn(Xtrain, ytrain); 35 | yhat = predictFn(model, Xtest); 36 | loss(testfolds{f}) = lossFn(yhat, ytest); 37 | end 38 | mu = mean(loss); 39 | se = std(loss)/sqrt(N); 40 | 41 | end 42 | 43 | 44 | -------------------------------------------------------------------------------- /metaTools/shadowFunction.m: -------------------------------------------------------------------------------- 1 | function shadowFunction(fname, output, quiet) 2 | % Shadow a function so that when it is called it silently does nothing 3 | % rather than its default behaviour. You can optionally specify a value 4 | % for the shadow to output. 5 | % 6 | % Also accepts a cell array of function names. 7 | % 8 | % **** Call removeShadows() when done **** 9 | % 10 | %% Examples 11 | % 12 | % shadowFunction('clc') 13 | % shadowFunction({'clear', 'cls', 'pause', 'keyboard', 'placeFigures', 'input'}); 14 | % removeShadows() 15 | % 16 | 17 | % This file is from matlabtools.googlecode.com 18 | 19 | SetDefaultValue(2, 'output', []); 20 | SetDefaultValue(3, 'quiet', false); 21 | warning('off', 'MATLAB:dispatcher:nameConflict'); 22 | if iscell(fname) 23 | cellfun(@(f)shadowFunction(f, output, quiet), fname); 24 | return 25 | end 26 | if ~quiet 27 | fprintf('shadowing %s\n', fname); 28 | if endswith(fname, '.m') 29 | fname = fname(1:end-2); 30 | end 31 | end 32 | 33 | if nargin < 2 34 | text = {sprintf('function %s(varargin)', fname); 35 | ''; 36 | 'end'; 37 | }; 38 | else 39 | 40 | text = {sprintf('function out = %s(varargin)', fname); 41 | ''; 42 | sprintf('%s', serialize(output)); 43 | 'end'; 44 | }; 45 | 46 | end 47 | path = fullfile(tempdir(), 'matlabShadow'); 48 | if ~exist(path, 'file') 49 | mkdir(fullfile(tempdir(), 'matlabShadow')); 50 | end 51 | writeText(text, fullfile(path, [fname, '.m'])); 52 | providePath(path); 53 | 54 | end 55 | -------------------------------------------------------------------------------- /graph/dfs_test.m: -------------------------------------------------------------------------------- 1 | % Test depth first search 2 | 3 | % This file is from matlabtools.googlecode.com 4 | 5 | %% A DAG 6 | % Do the example in fig 23.4 p479 of Cormen, Leiserson and Rivest (1994) 7 | u = 1; v = 2; w = 3; x = 4; y = 5; z = 6; 8 | n = 6; 9 | dag=zeros(n,n); 10 | dag(u,[v x])=1; 11 | dag(v,y)=1; 12 | dag(w,[y z])=1; 13 | dag(x,v)=1; 14 | dag(y,x)=1; 15 | dag(z,z)=1; 16 | 17 | directed = 1; 18 | root = 1; 19 | [d, pre, post, cycle, f, pred] = dfsPMTK(dag, [], directed); 20 | %[d2, pre2, post2, cycle2, f2, pred2] = dfsearchPMTK(dag, [], directed); 21 | %assert(isequal([d pre post cycle f pred], [d2 pre2 post2 cycle2 f2 pred2])) 22 | assert(isequal(d, [1 2 9 4 3 10])) 23 | assert(isequal(f, [8 7 12 5 6 11])) 24 | assert(cycle==1) 25 | 26 | % we can extract pre-order by sorting nodes based on discovery time 27 | [junk pre2] = sort(d) 28 | assert(isequal(pre, pre2)) 29 | 30 | % Other functions for same task 31 | [d2 dt ft pred2] = dfs(dag, root, 1) 32 | d3 = dt+1; d3(root)=1; 33 | [junk pre1] = sort(d3) 34 | 35 | G = sparse(dag); 36 | [disc, pred, closed]=graphtraverse(G,root,'method','dfs','directed',directed) 37 | 38 | 39 | 40 | %% Now give it an undirected cyclic graph 41 | %G = mk_2D_lattice(2,2,0); 42 | G = mkGrid(2,2,0); 43 | % 1 - 3 44 | % | | 45 | % 2 - 4 46 | [d, pre, post, cycle, f, pred] = dfsPMTK(G, [], 0); 47 | % d = [1 2 4 3] 48 | fprintf('cycle found (should be true)? %d\n', cycle) 49 | 50 | %% Now break the cycle 51 | G(1,2)=0; G(2,1)=0; 52 | [d, pre, post, cycle, f, pred] = dfsPMTK(G, [], 0); 53 | assert(~cycle) 54 | -------------------------------------------------------------------------------- /stats/Kfold.m: -------------------------------------------------------------------------------- 1 | function [trainfolds, testfolds] = Kfold(N, K, randomize) 2 | % Compute indices for K-fold cross validaiton 3 | % N = num data 4 | % K = num folds, if K=N, use leave-one-out CV 5 | % [trainfolds{i}, testfolds{i}] = indices of i'th fold 6 | % If randomize = 1, we shuffle the indices first 7 | % This is useful in case the data has some special ordering 8 | % such as all the positive examples before the negative ones 9 | % 10 | % Example: 11 | % [trainfolds, testfolds] = Kfold(100, 3) 12 | % testfolds{1} = 1:33, trainfolds{1} = 34:100 13 | % testfolds{2} = 34:66, trainfolds{2} = [1:33 67:100] 14 | % testfolds{3} = 67:100, trainfolds{3} = [1:66] 15 | % (last fold gets all the left over so has different length) 16 | % 17 | 18 | % This file is from matlabtools.googlecode.com 19 | 20 | 21 | if nargin < 3, randomize = 0; end 22 | if randomize 23 | setSeed(0); 24 | perm = randperm(N); 25 | else 26 | perm = 1:N; 27 | end 28 | 29 | ndx = 1; 30 | low = zeros(1, K); 31 | high = zeros(1, K); 32 | Nbin = zeros(1, K); 33 | testfolds = cell(1, K); 34 | trainfolds = cell(1, K); 35 | for i=1:K 36 | low(i) = ndx; 37 | Nbin(i) = fix(N/K); 38 | if i==K 39 | high(i) = N; 40 | else 41 | high(i) = low(i)+Nbin(i)-1; 42 | end 43 | testfolds{i} = low(i):high(i); 44 | trainfolds{i} = setdiff(1:N, testfolds{i}); 45 | testfolds{i} = perm(testfolds{i}); 46 | trainfolds{i} = perm(trainfolds{i}); 47 | ndx = ndx+Nbin(i); 48 | end 49 | 50 | if randomize 51 | restoreSeed; 52 | end 53 | 54 | end 55 | -------------------------------------------------------------------------------- /metaTools/hideFigures.m: -------------------------------------------------------------------------------- 1 | function hideFigures() 2 | % Hide all future generated figures until the showFigures() function is run 3 | 4 | % This file is from matlabtools.googlecode.com 5 | 6 | 7 | fprintf('figure display has been turned off\n'); 8 | set(0, 'defaultFigureVisible', 'off'); 9 | set(0, 'defaultAxesVisible', 'off'); 10 | 11 | tdir = tempdir(); 12 | fullpath = fullfile(tdir, 'matlabFigShadow'); 13 | if ~exist(fullpath, 'file'); 14 | mkdir(fullpath); 15 | end 16 | 17 | figfile = { 'function h = figure(varargin)' 18 | 'if nargin ==1 && isa(varargin{1}, ''double'')' 19 | ' if ismember(varargin{1}, get(0, ''Children''))' 20 | ' set(0, ''CurrentFigure'', varargin{1});' 21 | ' h = varargin{1};' 22 | ' else' 23 | ' h = builtin(''figure'', varargin{:});' 24 | ' set(gcf, ''Visible'', ''off'');' 25 | ' end' 26 | 'else' 27 | ' h = builtin(''figure'', varargin{:}, ''visible'', ''off'');' 28 | 'end' 29 | 'end' 30 | }; 31 | 32 | axesfile = { 'function h = axes(varargin)' 33 | 'if nargin ==1 && isa(varargin{1}, ''double'')' 34 | ' set(gcf, ''currentAxes'', varargin{1});' 35 | ' h = varargin{1};' 36 | 'else' 37 | ' h = builtin(''axes'', varargin{:}, ''visible'', ''off'');' 38 | 'end' 39 | 'end' 40 | }; 41 | 42 | writeText(figfile, fullfile(fullpath, 'figure.m')); 43 | writeText(axesfile, fullfile(fullpath, 'axes.m')); 44 | warning('off', 'MATLAB:dispatcher:nameConflict') 45 | providePath(fullpath); 46 | 47 | 48 | 49 | 50 | 51 | end 52 | -------------------------------------------------------------------------------- /metaTools/exportsvn.m: -------------------------------------------------------------------------------- 1 | function exportsvn(source, dest, exclusions, createEmpty) 2 | % Export and zip up a local svn repository ignoring .svn files 3 | % SOURCE: path to the root directory of the svn source 4 | % DEST: path to destination including zip file name 5 | % EXCLUSIONS: a cell array of directories to exclude from the 6 | % zip file. These should be relative to the root directory 7 | % EXAMPLE: 8 | % 9 | % exportsvn('C:\pmtk3', 'C:\users\matt\Desktop\pmtk3.zip', {'docs'}) 10 | 11 | % This file is from matlabtools.googlecode.com 12 | 13 | 14 | if nargin < 3, exclusions = {}; end 15 | if nargin < 4, createEmpty = {}; end 16 | 17 | destpath = fileparts(dest); 18 | [err1, output] = system(sprintf('svn export %s %s', source, fullfile(destpath, 'tmp'))); 19 | for i=1:numel(exclusions) 20 | ex = fullfile(destpath, 'tmp', exclusions{i}); 21 | if exist(ex, 'file') 22 | fprintf('%s excluded\n', exclusions{i}); 23 | system(sprintf('rmdir /Q /S %s', ex)); 24 | end 25 | end 26 | 27 | readmeText = {'This directory is left intentionally empty, and filled on demand.'}; 28 | for i=1:numel(createEmpty) 29 | fprintf('adding empty directory: %s\n', createEmpty{i}); 30 | emptyPath = fullfile(destpath, 'tmp', createEmpty{i}); 31 | mkdir(emptyPath); 32 | writeText(readmeText, fullfile(emptyPath, 'readme.txt')); 33 | end 34 | 35 | 36 | zip(dest, fullfile(destpath, 'tmp', '*')); 37 | err2 = system(sprintf('rmdir /Q /S %s', fullfile(destpath, 'tmp'))); 38 | if err1 || err2 39 | error('svn export failed:%s\n', output); 40 | end 41 | end 42 | --------------------------------------------------------------------------------