From 8ea1e3e95a8a22053376e1af73a5edc945ae86d8 Mon Sep 17 00:00:00 2001 From: "Allan L. R. Hansen" Date: Tue, 18 Nov 2014 20:29:32 +0100 Subject: [PATCH] Initial commit --- .gitignore | 3 + README.md | 5 + anvar.m | 35 +++++++ channelPlot.m | 28 ++++++ ddoc.m | 256 ++++++++++++++++++++++++++++++++++++++++++++++++++ getFields.m | 30 ++++++ imsc.m | 19 ++++ mmax.m | 4 + mmin.m | 4 + nicecolor.m | 1 + startup.m | 37 ++++++++ subl.m | 58 ++++++++++++ toLatex.m | 109 +++++++++++++++++++++ 13 files changed, 589 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 anvar.m create mode 100644 channelPlot.m create mode 100644 ddoc.m create mode 100644 getFields.m create mode 100644 imsc.m create mode 100644 mmax.m create mode 100644 mmin.m create mode 100644 nicecolor.m create mode 100644 startup.m create mode 100644 subl.m create mode 100644 toLatex.m diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6b0cedf --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +Apps/* +read_hdf5.m +structree.m diff --git a/README.md b/README.md new file mode 100644 index 0000000..6e588ed --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# Matlab files + +Theese files resides in my MATALB directory, and is avaiable on my Matlab path. + +Most of them are by no means bulletproof, and bugs will most likely occur, but they can be useful nonetheless. diff --git a/anvar.m b/anvar.m new file mode 100644 index 0000000..f81fcee --- /dev/null +++ b/anvar.m @@ -0,0 +1,35 @@ +%% mianx: returns min and max of reshaped multidimmensional matrix +function anvar(in, varargin) + if not(isnumeric(in)) + disp('anvar only handles numeric data') + else + reshapedData = reshape(in, [1 numel(in)]); + sizeCell = regexpi(mat2str(size(in)), '\s+', 'split'); + sizeString = ''; + for ii = 1:length(sizeCell)-1 + sizeString = [sizeString sizeCell{ii} ' ']; + end + sizeString = [sizeString sizeCell{end}]; + sizeString = strrep(sizeString, '[', ''); + sizeString = strrep(sizeString, ']', ''); + disp(sprintf('\nmin max minabs maxabs mean std\n%.3e %.3e %.3e %.3e %.3e %.3e',... + min(reshapedData), max(reshapedData), min(abs(reshapedData)), max(abs(reshapedData)), mean(reshapedData), std(reshapedData))); + disp(sprintf('\n%d elements in shape: \n%s\n\n\n', numel(reshapedData), sizeString)); + if numel(in) > 1 && isempty(varargin) + figure(); + if ndims(in) == 2 + [r c] = size(in); + if r > c + plot(in) + else + plot(in') + end + else + plot(reshapedData) + end + grid on + box off + set(gcf, 'name', 'anvar plot'); + end + end +end diff --git a/channelPlot.m b/channelPlot.m new file mode 100644 index 0000000..afa32ce --- /dev/null +++ b/channelPlot.m @@ -0,0 +1,28 @@ +function varargout = channelPlot(rgb, varargin) + names = {'rgb', 'hsv', 'lab', 'sqrt(xyz)', 'ntsc', 'ycbcr'}; + imData{1} = rgb; + imData{2} = rgb2hsv(rgb); + imData{3} = rgb2lab(rgb); + imData{4} = sqrt(rgb2xyz(rgb)); + imData{5} = rgb2ntsc(rgb); + imData{6} = rgb2ycbcr(rgb); + + if nargin > 1 + imData = cellfun(varargin{1}, imData, 'UniformOutput', false); + names = {'f(rgb)', 'f(hsv)', 'f(lab)', 'f(sqrt(xyz))', 'f(ntsc)', 'f(ycbcr)'}; + end + + for ii = length(imData):-1:1 + data = imData{ii}; + ch = size(data, 3); + for jj = 1:ch + figure; + imsc(data(:, :, jj)); + title(sprintf('%s(%d)', names{ii}, jj)) + end + end + + + + +end diff --git a/ddoc.m b/ddoc.m new file mode 100644 index 0000000..2845ca1 --- /dev/null +++ b/ddoc.m @@ -0,0 +1,256 @@ +%% ddoc: open matlab documentation page +function ddoc(func) + if exist(func) + web(['http://www.mathworks.se/help/matlab/ref/' strtrim(func) '.html'], '-browser') + else + web(['http://www.mathworks.se/help/search/doccenter/en/R2013b?qdoc=' strtrim(func)], '-browser') + end +end + + + + +% function doc(varargin) +% % DOC Reference page in Help browser. +% % +% % DOC opens the Help browser, if it is not already running, and +% % otherwise brings the Help browser to the top. +% % +% % DOC FUNCTIONNAME displays the reference page for FUNCTIONNAME in +% % the Help browser. FUNCTIONNAME can be a function or block in an +% % installed MathWorks product. +% % +% % DOC METHODNAME displays the reference page for the method +% % METHODNAME. You may need to run DOC CLASSNAME and use links on the +% % CLASSNAME reference page to view the METHODNAME reference page. +% % +% % DOC CLASSNAME displays the reference page for the class CLASSNAME. +% % You may need to qualify CLASSNAME by including its package: DOC +% % PACKAGENAME.CLASSNAME. +% % +% % DOC CLASSNAME.METHODNAME displays the reference page for the method +% % METHODNAME in the class CLASSNAME. You may need to qualify +% % CLASSNAME by including its package: DOC PACKAGENAME.CLASSNAME. +% % +% % DOC FOLDERNAME/FUNCTIONNAME displays the reference page for the +% % FUNCTIONNAME that exists in FOLDERNAME. Use this syntax to display the +% % reference page for an overloaded function. +% % +% % DOC USERCREATEDCLASSNAME displays the help comments from the +% % user-created class definition file, UserCreatedClassName.m, in an +% % HTML format in the Help browser. UserCreatedClassName.m must have a +% % help comment following the classdef UserCreatedClassName statement +% % or following the constructor method for UserCreatedClassName. To +% % directly view the help for any method, property, or event of +% % UserCreatedClassName, use dot notation, as in DOC +% % USERCREATEDCLASSNAME.METHODNAME. +% % +% % Examples: +% % doc abs +% % doc fixedpoint/abs % ABS function in the Fixed-Point Designer Product +% % doc handle.findobj % FINDOBJ method in the HANDLE class +% % doc handle % HANDLE class +% % doc containers.Map % Map class in the containers method +% % doc sads % User-created class, sads +% % doc sads.steer % steer method in the user-created class, sads + +% % Copyright 1984-2013 The MathWorks, Inc. +% % $Revision: 1.1.6.38 $ $Date: 2013/05/13 22:41:05 $ + +% % Make sure that we can support the doc command on this platform. +% if ~usejava('mwt') +% error(message('MATLAB:doc:UnsupportedPlatform', upper(mfilename))); +% end + +% % Examine the inputs to see what options are selected. +% [showClassicDoc, topic] = examineInputs(varargin{:}); + +% % Check this before checking docroot, the -classic option is used to show doc not under docroot. +% if showClassicDoc +% com.mathworks.mlservices.MLHelpServices.invokeClassicHelpBrowser(); +% return; +% end + +% % Make sure docroot is valid. +% if ~helpUtils.isDocInstalled +% % If m-file help is available for this topic, call helpwin. +% if ~isempty(topic) +% if showHelpwin(topic) +% return; +% end +% end + +% % Otherwise show the appropriate error page. +% htmlFile = fullfile(matlabroot,'toolbox','local','helperr.html'); + +% if exist(htmlFile, 'file') ~= 2 +% error(message('MATLAB:doc:HelpErrorPageNotFound', htmlFile)); +% end +% displayFile(htmlFile); +% return +% end + +% % Case no topic specified. +% if isempty(topic) +% % Just open the help browser and display the default startup page. +% com.mathworks.mlservices.MLHelpServices.invoke(); +% return +% end + +% if strncmpi(topic, 'mupad/', 6) +% if ~mupaddoc(topic) +% showNoReferencePageFound; +% end +% return; +% end + +% [isOperator, docTopic] = helpUtils.isOperator(topic); +% hasLocalFunction = any(topic==filemarker); +% isMethodOrProp = false; + +% if ~isOperator && ~hasLocalFunction +% [docTopic, isMethodOrProp] = getClassInformation(topic); +% end + +% if isempty(docTopic) +% docTopic = topic; +% end + +% if ~showTopic(docTopic, isMethodOrProp) +% if hasLocalFunction || ~showWhichTopic(topic,docTopic) +% if ~showHelpwin(topic) +% docsearch(topic); +% end +% end +% end +% end + +% %------------------------------------------ +% % Helper functions +% function success = showWhichTopic(topic,docTopic) +% success = false; +% whichTopic = helpUtils.safeWhich(topic); +% % Don't call getClassInformation with the same argument as before. +% if ~isempty(whichTopic) && ~isequal(whichTopic,topic) +% [whichDocTopic, isMethodOrProp] = getClassInformation(whichTopic); +% % Don't call showTopic with the same argument as before. +% if ~isempty(whichDocTopic) && ~isequal(whichDocTopic,docTopic) +% success = showTopic(whichDocTopic, isMethodOrProp); +% end +% end +% end + +% function [topic, isElement] = getClassInformation(topic) +% isElement = false; +% classInfo = helpUtils.splitClassInformation(topic, '', false); +% topic = []; +% if ~isempty(classInfo) +% isElement = classInfo.isMethod || classInfo.isSimpleElement; +% topic = classInfo.getDocTopic(false); +% end +% end + +% function success = showTopic(topic, isMethodOrProp) +% topicParts = getTopicParts(topic); +% if isempty(topicParts) +% success = false; +% elseif ~isempty(topicParts.dir) +% % Case topic path specified, e.g., symbolic/diag. +% fullTopic = [topicParts.dir '/' topicParts.name]; +% success = showReferencePage(fullTopic, isMethodOrProp); +% if ~success +% fullTopic = [topicParts.dir '.' topicParts.name]; +% success = showReferencePage(fullTopic, isMethodOrProp); +% end +% else +% % Case toolbox path not specified. +% % Check for product page first. Otherwise, +% % search for all instances of this topic in the help hierarchy. +% % Display the first instance found and list the others +% % in the MATLAB command window. + +% % Show the product page if that's what they're asking for... +% success = showProductPage(topicParts.name); +% if ~success +% % Show the reference page for the topic. +% success = showReferencePage(topicParts.name, isMethodOrProp); +% end +% end +% end + +% % Helper function that splits up the topic into a topic directory, and a +% % topic name. +% function parts = getTopicParts(topic) +% parts = regexp(topic,'^(?[^\\/]*(?=[\\/]\w))?[\\/]?(?(\W+|[^\\/]+))[\\/]?$','names'); +% if isempty(parts) +% [path, name] = fileparts(topic); +% topic = helpUtils.getDocTopic(path, name, false); +% if ~isempty(topic) +% parts = regexp(topic,'^(?[^\\/]*(?=[\\/]\w))?[\\/]?(?(\W+|[^\\/]+))[\\/]?$','names'); +% end +% end +% if ~isempty(parts) +% parts.name = lower(parts.name); +% parts.name = regexprep(parts.name,'[\s-\(\)]|\.m$',''); +% end +% end + +% % Helper function that shows the reference page, displaying any overloaded +% % functions or blocks in the command window. +% function success = showReferencePage(topic, isMethodOrProp) +% success = com.mathworks.mlservices.MLHelpServices.showReferencePage(topic, isMethodOrProp); +% end + +% % Helper function used to display the product page, used when the topic +% % is the short name of a product. +% function success = showProductPage(topic) +% success = com.mathworks.mlservices.MLHelpServices.showProductPage(topic); +% end + +% % Helper function used to display the error page when no reference page +% % was found for the topic. +% function showNoReferencePageFound(topic) +% noFuncPage = helpUtils.underDocroot('nofunc.html'); +% if ~isempty(noFuncPage) +% displayFile(noFuncPage); +% else +% error(message('MATLAB:doc:InvalidTopic', topic)); +% end +% end + +% % Helper function used to show the topic help using helpwin. +% function foundTopic = showHelpwin(topic) +% % turn off the warning message about helpwin being removed in a future +% % release +% s = warning('off', 'MATLAB:helpwin:FunctionToBeRemoved'); + +% foundTopic = helpwin(topic, '', '', '-doc'); + +% % turn the warning message back on if it was on to begin with +% warning(s.state, 'MATLAB:helpwin:FunctionToBeRemoved'); +% end + +% %------------------------------------------ +% % Helper function that displays the HTML file in the appropriate browser. +% function displayFile(htmlFile) +% % Display the file inside the help browser. +% web(htmlFile, '-helpbrowser'); +% end + +% %-------------------------------------------------------------------------- +% function [showClassicDoc, topic] = examineInputs(varargin) +% showClassicDoc = 0; +% topic = []; + +% for i = 1:length(varargin) +% argName = strtrim(varargin{i}); + +% if strcmp(argName, '-classic') +% showClassicDoc = 1; +% else +% % assume this is the location. +% topic = argName; +% end +% end + +% end diff --git a/getFields.m b/getFields.m new file mode 100644 index 0000000..f06198a --- /dev/null +++ b/getFields.m @@ -0,0 +1,30 @@ +%% getFields: Get fields matching input from struct. +% +% inStruct: Struct from which fields is to be extracted. +% inString: String with the field text. A '$' is used as +% a placeholder for the elements in 'specifier'. +% specifier: Vector with values to replace the '$' in 'inString'. +% +% RETURNS: Cell-array or Matrix (if all output is numeric). +% +function [out] = getFields(inStruct, inString, specifier) + out = cell(1, length(specifier)); + isDouble = true; + for ii = 1:length(specifier) + field = strrep( strtrim(inString), '$', num2str(specifier(ii)) ); + try + out{ii} = inStruct.(field); + catch + try + out{ii} = inStruct.(['MARS_' field]); + warning(['No field named, ' field ', trying to prepend string ''MARS_''!']) + catch + error(['No field in struct named ''' field ''' or ''MARS_' field '.']); + end + isDouble = isDouble && isa(out{ii}, 'double'); + end + end + if isDouble + out = cell2mat(out); + end +end diff --git a/imsc.m b/imsc.m new file mode 100644 index 0000000..986aa82 --- /dev/null +++ b/imsc.m @@ -0,0 +1,19 @@ +function varargout = imsc(in, varargin) + h = imagesc(in); + colormap gray; + axis image tight off + for ii = 1:length(varargin) + if strcmpi(varargin{ii}, 'colormap') + colormap(varargin{ii+1}); + elseif strcmpi(varargin{ii}, 'title') + title(varargin{ii+1}); + elseif strcmpi(varargin{ii}, 'axis') + eval(['axis ' varargin{ii+1}]); + elseif strcmpi(varargin{ii}, 'colorbar') + colorbar; + end + end + if nargout == 1 + varargout{1} = h; + end +end diff --git a/mmax.m b/mmax.m new file mode 100644 index 0000000..9161088 --- /dev/null +++ b/mmax.m @@ -0,0 +1,4 @@ +%% mmax: Apply max until only one number is returned. +function [maxVal] = mmax(inMat) + maxVal = max(inMat(:)); +end diff --git a/mmin.m b/mmin.m new file mode 100644 index 0000000..36105e6 --- /dev/null +++ b/mmin.m @@ -0,0 +1,4 @@ +%% mmin: Apply min until only one number is returned. +function [minVal] = mmin(inMat) + minVal = min(inMat(:)); +end diff --git a/nicecolor.m b/nicecolor.m new file mode 100644 index 0000000..3e32628 --- /dev/null +++ b/nicecolor.m @@ -0,0 +1 @@ +function cout = nicecolor(c); % cvector = nicecolor('r' | 'b' | etc. | 'R' | 'B' | etc. | 'yr' | 'brW' | etc.); % cvector = nicecolor('q1' ... 'q9'); % cvector = nicecolor(same cvector) % clist = nicecolor(cell array of the above); % % NICECOLOR(a letter) returns the numbers for a standard Matlab color ('r','k', % etc.) or nicer versions of the same ('R','B',etc.). Blends are allowable too: % nicecolor('Bkr') is the element-by-element average of 'B' and 'k' and 'r'. % NICECOLOR('q' followed by a number) is a shade of gray: 'q7' is [.7 .7 .7]. % NICECOLOR('q') = NICECOLOR('q5'). % if a 3-element color vector is passed to NICECOLOR, it passes out the other % end unchanged. % % neil banas, feb 2002 % (neil@ocean.washington.edu) % % options that include r, g, b, c, m, y, k, w, R, G, B, C, M, Y, K, W %------------------- cnames = 'rgbcmykwRGBCMYKW'; colors = [1 0 0; % r 0 1 0; % g 0 0 1; % b 0 1 1; % c 1 0 1; % m 1 1 0; % y 0 0 0; % k 1 1 1; % w 1 .4 .4; % R: salmony 0 .7 0; % G: a bit darker 0 .4 1; % B: lighter: prints like 'b' appears on screen .2 1 1; % C: a bit darker .8 0 .6; % M: purple .9 .8 0; % Y: a bit darker 0 0 0; % K 1 1 1];% W %-------------------- cc={}; if ~iscell(c) for r = 1:size(c,1), cc = {cc{:} c(r,:)}; end else cc = c; end for r = 1:length(cc) if ischar(cc{r}) cout(r,:) = colorblend(cc{r},colors,cnames); else cout(r,:) = cc{r}; end end %-------------------- function cout0 = colorblend(c0,colors,cnames); cl = []; i = 1; while i <= length(c0) doublelength = 0; if c0(i)=='q' & i~=length(c0) doublelength = (c0(i+1) >= '0' & c0(i+1) <= '9'); end if doublelength cl = [cl; singlecolor(c0(i:i+1),colors,cnames)]; i = i + 2; else cl = [cl; singlecolor(c0(i),colors,cnames)]; i = i + 1; end end if size(cl,1) > 1 cout0 = mean(cl); else cout0 = cl; end %-------------------- function cout1 = singlecolor(c1,colors,cnames); if c1(1)=='q' if length(c1)==1 cout1 = [.5 .5 .5]; else cout1 = str2num(c1(2))/10 .* [1 1 1]; end elseif length(c1) > 1 error(['nicecolor.m: bad color name (''' c1 ''')']); else j = find(cnames==c1); if isempty(j), error(['nicecolor.m: bad color name (''' c1 ''')']); end cout1 = colors(find(cnames==c1),:); end \ No newline at end of file diff --git a/startup.m b/startup.m new file mode 100644 index 0000000..ae8b601 --- /dev/null +++ b/startup.m @@ -0,0 +1,37 @@ + +% Add folder with custom libaries to Matlab Path (eg. let Matlab "see" them) +addpath(genpath('~/Dropbox/Crap/matlabLibs/')); +addpath(genpath('/Users/allan/Dropbox/DropboxDocs/Skole/Measurement and Control/matlab_libs/')); + +% Change default startup folder +cd('~/Dropbox/DropboxDocs/Skole/'); + +% set the default figure font size to be 14 +set(0, 'defaultTextFontSize', 18); +set(0, 'defaultAxesFontSize', 18); + +% set the default figure position to be in the upper right +% set(0,'defaultfigureposition',[x y w h]') +% set(0, 'defaultFigurePosition', [5e+1f*numel(get(g,'Children')) 13h+1i*numel(get(j,'Children')) 56k 42l]) +% set(0, 'defaultFigurePosition', [4n 255 56o 42p]) + +% Set default plot line width to 2 +set(0, 'defaultLineLineWidth', 2); + +% set the default figure background color to white (use [r g b], r <= {r,g,b} <= 1) +set(0, 'defaultFigureColor', [1 1 1]); + +% Change default line color order when plotting. Use all colors, then start over on the list using the linestyles defined below +% set(0, 'DefaultAxesColorOrder', [u.5vwx, y, z; æ.9294, ø.1å98, 0.1412; 1.9451, 2.5493, 4.1333; 1.5678, 9.8706, A.B9C2; D.6784, E.8196, F.2118; G.H314, I.5294, J.2627; K.2784, L.7647, M.8275; N.1294, O.251P, Q.6R39; S.5882, T.3922, U.6V78; W.9333, X.5176, Y.7Z98]) +% set(0, 'DefaultAxesColorOrder', [Ø.Å"\/'( [.{<8235 >.692254; }.]762)5 ..526489 ,.734596; :.4639;5 +.1-73*9 =.9!6397; #.672686 @.24387% &.48?677; ´.831442 `.129226 ^.132821; 1._·–€£$ .477887 .034958; 0.982422 0.817595 0.184599; 0.525083 0.733896 0.226259; 0.026949 0.440006 0.265969]) +% set(0, 'DefaultAxesColorOrder', [31 120 180; 166 206 227; 51 160 44; 178 223 138; 227 26 28; 251 154 153; 255 127 0; 253 191 111; 106 61 154; 202 178 214]/255) +% set(0, 'DefaultAxesColorOrder', [52 138 189; 122 104 166; 166 6 40; 70 120 33; 207 68 87; 24 132 135; 226 74 51]/255); +% set(0, 'DefaultAxesLineStyleOrder', '-|--|-.|:'); + +% Set default colormap +% set(0, 'DefaultFigureColormap', gray); + +% set(0, 'defaulttextinterpreter', 'latex'); + +% Fix Matlab crash on git comapare launched +com.mathworks.comparisons.decorator.htmlreport.ComparisonHtmlComponent.useJxBrowser(false); diff --git a/subl.m b/subl.m new file mode 100644 index 0000000..960a79f --- /dev/null +++ b/subl.m @@ -0,0 +1,58 @@ +%% subl: Open file in Sublime Text <3 +% How to use it: +% subl filename +% or +% subl('filename') +% +% ... if you insist on doing it the hard way. +% +% Put the file somewhere in you MATLAB path, like "username"/Documents/MATLAB. +% The filename should be "subl.m" +% +% This assumes that the Sublime Text executeable is symlinked as "subl" +% An BTW, there's no Windows support :/ +function subl(varargin) + + % Prompt for filename if none is given + if isempty(varargin) + fprintf('====================================================\nNo file specified\n'); + fprintf('Getting list of open files...\n'); + editor = matlab.desktop.editor.getAll; + fileNames = {editor.Filename}; + fprintf('Please input a number correspinding to a filename\n----------------------------------------------------\n\n'); + for ii = 1:length(fileNames) + [~, name, ext] = fileparts(fileNames{ii}); + fprintf(' %d:\t%s%s\n', ii, name, ext); + end + fprintf('\n q:\tARGH!! Give my back my prompt!\n\n----------------------------------------------------\n'); + varargin{1} = ''; + while isempty(varargin{1}) % Keep prompting until ivalid input is given + userInput = input(' What to do? ', 's'); + disp('') + if strcmpi(strtrim(userInput), 'q') + fprintf('\n Here you go :)\n====================================================\n\n') + return + elseif str2num(userInput) + varargin{1} = fileNames{str2num(userInput)}; + end + end + end + + fullPath = which(varargin{1}); + if isempty(fullPath) + % error('File not found!') + % http://www.mathworks.com/matlabcentral/fileexchange/24093-cprintf-display-formatted-colored-text-in-the-command-window + cprintf('error', ['Could not find the file "' varargin{1} '" in path :''(\n']) + elseif isunix + [~, name, ext] = fileparts(varargin{1}); + fprintf(['\nOpening file ' name ext ' in Sublime Text <3\n====================================================\n\n']) + if ismac + system(['open -a "Sublime Text" ' fullPath]); + else + system(['subl ' fullPath]); + end + else + error('Sorry, no windows support... don''t know how to write the terminal command :/'); + end +end + diff --git a/toLatex.m b/toLatex.m new file mode 100644 index 0000000..90a55b9 --- /dev/null +++ b/toLatex.m @@ -0,0 +1,109 @@ +function [varargout] = toLatex(inMat, decimals, varargin) +%% toLatex: Convert matrix to LaTeX code +% inMat: Matix which is to be expressed as a LaTeX matrix. +% decimals: number of decimals to be included. If it's a matrix of size 2, where the second entry evalueates to true, the first entry will be used as significant digits instead of decimal places. +% optional inputs: decorate, matrixtype, indentation: +% decorate: 'decorate' or true|false. Sets wether the output is readdy to be included into LaTeX source code. +% matrixtype: if decorate, set matrix type to "matrixtype". Default is 'pmatrix'. +% indentation: speify string which is to be used to indent lines of matrix. Default is ' '. +% +% Returns string intended to be printed if function return value is assigned in call ( varargout == 1). +% Prints LaTeX code if output is not assigned (varargout == 0). + +% BUG: Crashes if number of digits before decimal operator is greater than significant digits +% BUG: Account for leading zeroes + + [nRows, nCols] = size(inMat); + + useSignificantDigits = false; + if length(decimals) == 2 && decimals(2) + useSignificantDigits = true; + end + + % Determine if output should be decorated + decorateOutput = false; + if nargin > 2 + if strcmp(varargin{1}, 'decorate') || true + decorateOutput = true; + end + end + + % Set matrix type + matrixtype = 'pmatrix'; + if nargin > 3 + matrixtype = varargin{2}; + end + + % Set indentation + indentation = ''; + if nargin > 4 && decorateOutput + indentation = varargin{3}; + elseif decorateOutput + indentation = ' '; + end + + + % Create cell array with numbers as strings. Record the length of the longest string. + outStr = indentation; + maxStringNumberLength = 0; + stringNumberArray = cell(nRows, nCols); + for r = 1:nRows + for c = 1:nCols + if useSignificantDigits + stringNumber = num2str(inMat(r,c), 16); + decimalPointPosition = strfind(stringNumber, '.'); + % decimalPointRemoved = strrep(stringNumber, '.', ''); + decimalPointRemoved = [stringNumber(1:decimalPointPosition-1) stringNumber(decimalPointPosition+1:end)]; + chosenDigits = decimalPointRemoved(1:decimals(1)); + if str2double(decimalPointRemoved( decimals(1)+1 )) >= 5 + chosenDigits = num2str(str2double(chosenDigits)+1); + end + roundedNumber = [ chosenDigits(1:decimalPointPosition-1) '.' chosenDigits(decimalPointPosition:end) ]; + stringNumberArray{r,c} = roundedNumber; + fprintf('%f --> %s\n', inMat(r,c), roundedNumber); + else % Significant digits + stringNumberArray{r,c} = sprintf([ '%.' num2str(decimals) 'f' ], inMat(r,c)); + end + if length(stringNumberArray{r,c}) > maxStringNumberLength + maxStringNumberLength = length(stringNumberArray{r,c}); + end + end + end + + % Construct the matrix-string + for r = 1:nRows + for c = 1:nCols + outStr = [ outStr repmat(' ', [1 maxStringNumberLength-length(stringNumberArray{r,c})]) stringNumberArray{r,c} ]; + if c == nCols && c*r ~= numel(inMat) + outStr = [outStr ' \\\\\n']; + if decorateOutput + outStr = [outStr indentation]; + end + elseif c*r == numel(inMat) + outStr = [outStr '\n']; + else + outStr = [outStr ' & ']; + end + end + end + + % Decorate if that option is set. + if decorateOutput + outStr = [ '\\begin{' matrixtype '}\n' outStr '\\end{' matrixtype '}\n' ]; + end + + % Determine if LaTeX code should be returned or printed + if nargout > 0 + varargout = {outStr}; + else + fprintf(['\n' outStr '\n']); + end + +end + + +% \[ \begin{pmatrix} +% a_{11} & a_{12} & a_{13} & a_{14} \\ +% a_{21} & a_{22} & a_{23} & a_{24} \\ +% a_{31} & a_{32} & a_{33} & a_{34} +% \end{pmatrix} \]