Matlab Scripts and Functions for Chemical and Biochemical Education

This set of programs includes material created for general chemistry and biochemistry courses. They are either visual demonstrations of chemical and physical concepts or simple simulations of fundamental models in chemical and biochemical kinetics and thermodynamics. The older programs were tested under R2014b, Mac OS X El Capitan, but I think they should work with most versions of Matlab and most OS's. For University of Maryland students, Matlab can be downloaded via Terpware. Some of these programs make use of external functions available for download at the MathWorks® File Exchange, http://www.mathworks.com/matlabcentral/fileexchange/. I also provide a very simple and specialized Matlab tutorial meant to enable students to run and use canned programs, as opposed to the usual tutorials that lead them into programming Matlab. Making this material widely available was supported and inspired by the Elevate Fellows program run through the Teaching and Learning Transformation Center here at the University of Maryland College Park.

External functions export_fig, partitions, mtit, and dsxy2figxy from the Matlab File Exchange of useful user-contributed programs are needed for some of my programs. You may need to create a Matlab account to get these files. I am unsure of the protocol for providing them here so I am not doing it.

export_fig: http://www.mathworks.com/matlabcentral/fileexchange/23629-export-fig

partitions: http://www.mathworks.com/matlabcentral/fileexchange/12009-partitions-of-an-integer

mtit: http://www.mathworks.com/matlabcentral/fileexchange/3218-mtit--a-pedestrian-major-title-creator

dsxy2figxy: http://www.mathworks.com/matlabcentral/fileexchange/30347-sigplot/content/sigplot/sigplot/BasicFunctions/dsxy2figxy.m. Note this file is not findable by searching within the File Exchange -- it is within the Sigplot package. Just Google for it if necessary.

Each of my functions or scripts has a comment section (in green type) telling the user what it does and expects. They should be self-explanatory.

For the newer programs (2025 and later, written with help from Claude) the Download link goes to a single .m file. For the older ones it goes to a zip file that includes all of the files needed to run the scripts except for the external ones above. Sometimes it's just one file. Many of the programs also have a browser version that needs no Matlab, linked in their descriptions.

Comments welcome. If you have suggestions for improvement, or better yet improved code, please let me know.

See also my companion page of Excel spreadsheets.

Back to Jason Kahn's home page or listing of other teaching resources

Matlab programs:

Acid-Base Titration Curves. Download weakweak10.m. Back to List. Browser version: titration of any acid or base with any other.

function [titr, numlabel, figh] = weakweak10(CA,CB,volA,volB,varargin)

% Plots a titration curve for titrating a weak acid with a weak base
%  or vice versa. Includes several options for display of e.g. speciation
%  and plotting multiple curves on the same axes.
% The required first four arguments are: CA,CB,volA,volB
% The optional arguments in varargin, in order, are pKA(HA),pKB(B),hhplot=0 or 1,
%    forrev='f' or 'r',numlabel,'DualPlot' or 'OnePlot','NoPoints' or ''
% The last seven default to (-5,-5,0,'f',0,'OnePlot',show points).
% The last seven must be given in order.
% The default pKa of HA and pKb of B (-5 each) give a strong acid/strong base titration.
% numlabel=0 opens a new figure; pass the returned numlabel to another call in order to overlay
%    a new plot on the frontmost figure (which will be the figure you just made if you do
%    it with the next command). Numlabel increments to keep plots and legends
%    looking good.
% 'DualPlot' creates a new figure with a pH+derivative panel and a speciation panel.
%    Returns numlabel unchanged so the next call resumes on the original figure.
%    DualPlot is not supported for reverse titrations.
% [titr,numl,figh] = weakweak10(...) also captures the figure handle, which can be
%    used to bring a specific figure to the front (figure(figh)), save it to disk
%    (exportgraphics(figh,'file.png','Resolution',300) or saveas(figh,'file.fig')),
%    resize it (figh.Position=[x y w h]), or close it (close(figh)).
%    This is especially useful in the DualPlot workflow: save the handle from the
%    first call, then after the DualPlot call use figure(figh) to reliably restore
%    focus to the original figure instead of clicking.
%
% BUFFER CAPACITY: set the flag bufcapMethod near the top of the code (not an argument):
%  'dynamic' (default): dynamic buffer capacity, beta_V = |dc/dpH|, where c is the
%      concentration of added titrant in the flask, c = C*V/(V0+V). Follows the actual
%      titration, including the dilution caused by each addition.
%      A. M. Michalowska-Kaczmarczyk & T. Michalowski, J. Solution Chem. 44, 1256-1266 (2015).
%  'static': classical buffer value of Van Slyke, strong base per liter per pH at fixed
%      composition: beta = ln10*([H+] + Kw/[H+] + CA*Ka*[H+]/(Ka+[H+])^2
%                                + CB*(Kw/Kb)*[H+]/(Kw/Kb+[H+])^2)
%      D. D. Van Slyke, J. Biol. Chem. 52, 525-570 (1922).
%  In the buffer region, dynamic ~ static * V0/(V0+V), so the dynamic value is smaller
%  and peaks earlier; outside the buffer region they differ more.
%
% The program outputs a matrix as the titr variable with columns:
%  vol of A, vol of B, pH, [HA], [A-], [B], [BH+], buffer capacity (as chosen above)
%
% Jason Kahn, U Maryland, 03/24/2025, updated 10/29/2026 (weakweak10)
%    with help from Claude

Diprotic Acid and Base Titration Curves. Download diprotic3.m. Download diprotic3r.m. Back to List. Browser version: diprotic titrations.

function [titr, numlabel] = diprotic3(CA,CB,volA,volB,varargin)

% Titrates a diprotic weak acid H2A (CA, volA) with weak base B (CB, volB).
% Also displays speciation curves and buffer capacity.
% Returns titr: [Bvol, pH, H2A, HA-, A2-, B, BH+, bufcap]
% Jason Kahn U Maryland 10/18/2018, updated 4/21/2026 with varargin/overlay/derplot
%    with help from Claude
%
% Optional args (in order): pKAA1, pKAA2, pKBB, hhplot, numlabel, derplot, 'NoPoints'
% pKAA1, pKAA2 are the two pKa's of H2A (pKAA1 must be < pKAA2)
% pKBB is the pKb of base B
% Defaults: pKAA1=-5, pKAA2=-5, pKBB=-5, hhplot=0, numlabel=0, derplot=1, show points
% numlabel=0 opens a new figure; pass the returned numlabel to overlay on the same figure.
% derplot=0 suppresses the dpH/dV axis on the top panel.
%
% Examples:
% [titr,numl] = diprotic3(0.1,0.05,100,500,2.75,6.31,3.5,0);
% [titr,numl] = diprotic3(0.1,0.05,100,500,2.75,6.31,3.5,0,numl);    % overlay
% [titr,numl] = diprotic3(0.1,0.05,100,500,2.75,6.31,3.5,0,0,0);      % no derivative
% [titr,numl] = diprotic3(0.1,0.05,100,500,2.75,6.31,3.5,0,0,1,'NoPoints'); % no data points

function [titr, numlabel] = diprotic3r(CB,CA,volB,volA,varargin)

% Titrates a dibasic base B (CB, volB) with two pKas with acid HA (CA, volA).
% Also displays speciation curves and buffer capacity.
% Returns titr: [Avol, pH, H2B(2+), BH+, B, HA, A-, bufcap]
% Jason Kahn U Maryland 4/21/2026, updated with varargin/overlay/derplot
%    with help from Claude
%
% Optional args (in order): pKAB1, pKAB2, pKAt, hhplot, numlabel, derplot, 'NoPoints'
% pKAB1, pKAB2 are pKa's of BH+ and H2B2+ (pKAB1 must be < pKAB2)
% Defaults: pKAB1=-5, pKAB2=-5, pKAt=-5, hhplot=0, numlabel=0, derplot=1, show points
% numlabel=0 opens a new figure; pass the returned numlabel to overlay on the same figure.
% derplot=0 suppresses the dpH/dV axis on the top panel.
%
% Examples:
% [titr,numl] = diprotic3r(0.1,0.05,100,500,2.75,6.31,3.5,0);
% [titr,numl] = diprotic3r(0.1,0.05,100,500,2.75,6.31,3.5,0,numl);    % overlay
% [titr,numl] = diprotic3r(0.1,0.05,100,500,2.75,6.31,3.5,0,0,0);      % no derivative
% [titr,numl] = diprotic3r(0.1,0.05,100,500,2.75,6.31,3.5,0,0,1,'NoPoints'); % no data points

Triprotic Acid Titration Curves. Download phosphoric_titration.m. Back to List. Browser version: triprotic titrations and the isoelectric point.

function titr = phosphoric_titration(CA0, CB0, VAcid, Vbase, pK, hhplot)

% Titration of a triprotic acid H3A (default: phosphoric acid) with a strong base (NaOH).
% The pH at each point is the one root of the charge balance
%    [Na+] + [H+] = [H2A-] + 2[HA2-] + 3[A3-] + [OH-]
% [algorithm from Claude; I, JDK, used the roots function in Matlab for the mono- and diprotic programs]
% Root found by bisection on log10[H+] (every term moves in one direction as [H+] rises,
% so there is exactly one root). Activities are taken equal to concentrations.
% Marks the three equivalence points (green, dashed, filled dots) and the points halfway
% to each (red, dotted, open dots), with their pH values, and the three pKa's.
%
% All inputs are optional, in order (defaults in brackets):
%  CA0  acid concentration, M [0.100]
%  CB0  NaOH concentration, M [1.00]
%  VAcid    volume of acid, mL [100]
%  Vbase  largest volume of NaOH, mL [4/3 of the third equivalence volume]
%  pK    the three pKa's, default [2.1 7.2 12.3]
%  hhplot 1 to draw the Henderson-Hasselbalch estimate (dashed), 0 not to [1]
% Returns titr = [volume of NaOH (mL), pH].
%
% Examples:
%  phosphoric_titration;                    % 100 mL 0.1 M H3PO4 with 1 M NaOH
%  phosphoric_titration(0.1, 0.1);          % with 0.1 M NaOH
%  phosphoric_titration(0.1, 1, [], [], [], 0);  % without the Henderson-Hasselbalch line
%  titr = phosphoric_titration(0.1, 1, 100, 40, [3.13 4.76 6.40]);  % citric acid
%
% The Henderson-Hasselbalch estimate fails silently near each equivalence point and for a
% strong first proton; it then runs off the plot.
%
% Jason Kahn, U Maryland, 11/2/2026, with help from Claude

Chemical Thermodynamics: Illustrate relationships among ΔG, ΔG°, Q, K, and molar G’s. Download TotalG.m. Download TotalG_anim.m. Back to List. Browser version: free energy of an A ⇌ B mixture.

function [ GvsX ] = TotalG(G0A,G0B,varargin)

% TotalG(G0A,G0B,totmoles,expf);, last two arguments are optional
%  Calculates free energy of a mixture of A <-> B as a function of mole
%      fraction, plots several graphs showing patterns
% Jason Kahn U Maryland 11/26/2018  version 1.1
%  Input G0A = standard state molar free energy of A, G0B for B
%      totmoles = total # of moles. Default is 1.
%  (Of course could just specify a difference but this can be used to
%      demonstrate that only the difference matters.)
%  Set expf = 'y' if you want to call export_fig to output, default is no.
%  The molar free energy of each species is the standard state free
%      energy plus RT ln[concentration], with [B] = X*totmoles and
%      [A] = (1-X)*totmoles. Units of G are in RT for simplicity
%  X is the mole fraction of B, so 1-X is the mole fraction of A
%  Calculation assumes volume of 1 L, so 1 mole of A corresponds to 1 M A etc.
%  Returns a matrix of Total G versus X
%  Uses export_fig if and only if you want to make images.
%  Download export_fig from http://www.mathworks.com/matlabcentral/fileexchange/23629-exportfig
%  Calls mtit function to place overall title above plots
%  DL mtit from http://www.mathworks.com/matlabcentral/fileexchange/
%          3218-mtit--a-pedestrian-major-title-creator
%  Also requires dsxy2figxy function, which makes arrows, from
%  https://www.mathworks.com/matlabcentral/fileexchange/30347-sigplot/content/sigplot/sigplot/BasicFunctions/dsxy2figxy.m

function TotalG_anim(G0A,G0B_hi,G0B_lo,varargin)

% TotalG_anim(G0A,G0B_hi,G0B_lo,varargin);, varargin arguments are optional
%  Calculates free energy of a mixture of A <-> B as a function of mole
%      fraction, plots several graphs showing patterns
% This version makes a series of graphs with varyng G0B, suitable for
% making into a movie in e.g. QuickTime.
% Jason Kahn U Maryland
% Movie version 5/7/2025  version 1.1
%  Input G0A = standard state molar free energy of A, G0B for B
%      totmoles = total # of moles (if we assume 1 L of course this is total molar). Default is 1.
%  (Of course could just specify a difference in free energy but this can be used to
%      demonstrate that only the difference matters.)
%  The molar free energy of each species is its standard state free
%      energy plus RT ln []. Units of G are in RT for simplicity
%  X is the mole fraction of B, so 1-X is the mole fraction of A
%  Calculation assumes volume of 1 L, so 1 mole of A corresponds to 1 M A etc.
%  Makes the figures only; drawGgraph returns Total G versus X
%  Uses exportgraphics if and only if you want to make images (used to
%      use esportfig but it crashes and locks up a lot)
%      export_fig is at  http://www.mathworks.com/matlabcentral/fileexchange/23629-exportfig
%  Calls the mtit function to place overall title above plots
%  DL mtit from http://www.mathworks.com/matlabcentral/fileexchange/
%          3218-mtit--a-pedestrian-major-title-creator
%  Set expf = 'y' if you want to call exportgraphics function to output to files, default is no.
%  Also requires dsxy2figxy function, which makes arrows, from
%  https://www.mathworks.com/matlabcentral/fileexchange/30347-sigplot/content/sigplot/sigplot/BasicFunctions/dsxy2figxy.m

Binding Curves and Titrant Depletion. Download Binding_DT_script2.m. Back to List. Browser version: binding curves and titrant depletion.

A script (not a function): edit Kd and DT near the top, then run it. Makes binding curves with linear and logarithmic axes, compares evenly spaced and geometric series of protein concentrations, and shows the effects of DT and Kd. Uses the full quadratic for single-site binding (function fullbind, at the end of the file).

% Script to illustrate simple binding curves
% Presents linear and semilog plots, shows how a geometric series is the better
% choice for protein concentrations, and shows the effects of DT and Kd.
% This version meant to show the effect of having DT be too large w.r.t
% Kd, needs a lot of cosmetic work.

Chemical Kinetics I (via numerical integration). Download zip file. Back to List.

function [ T1,Y1 ] = ABC_eq_kin(varargin)

%ABC_eq_kin Simulates kinetics of the reaction scheme below via numerical
%  integration of differential rate laws
%   A <--> B <--> C
% Jason Kahn U Maryland 9/27/2016 version 1.01
% Arguments (all optional, but order is fixed and no skipping) in order are
%    A0,B0,C0,k1,k2,k3,k4,t_end,savefig
% Returns a vector of times and an array of []'s of A, B, C
% Makes one plot, a large plain-vanilla concentration vs. time plot
% Typical call with default rate constants and initial concentrations:
%    [t,Y]= ABC_eq_kin(1,0,0,6,9,2,1,3,0);
%   ABC_eq_kin(1,0,0,60,30,2,1,2.5,0); gives very fast initial
%    equilibration and slow second step
%    ABC_eq_kin(1,0,0,6,4,2,1,5,0); intermediate behavior
%    ABC_eq_kin(1,0,0,6,0,2,0,3,0); setting reverse rates = 0 gives
%    classic A->B->C behavior
%    ABC_eq_kin(1,0,0,.6,.4,200,100,5,0); shows first step rate limiting
%    and effecitvely instantaneous equilibration of B and C
%    ABC_eq_kin(1,0,0,.6,.4,1,.5,8,0); illustrates lag in appearance of C
%   Calls function ABC_eq_kin_deltas (at the end of this file) to provide differential rates
%   Calls function export_fig if and only if savefig flag is set to 1
%    Download export_fig from http://www.mathworks.com/matlabcentral/fileexchange/23629-exportfig

Chemical Kinetics II (via numerical integration). Download zip file. Back to List.

function [ T1,Y1 ] = ABCDEFkin_2(varargin)

%ABCDEFkin_2 Simulates kinetics of the reaction scheme below via numerical
%   integration of differential rate laws
%   A + B <-> C + D, D -> E, C <-> F
% Jason Kahn U Maryland 10/21/2016 version 1.1
% Arguments (all optional, but order is fixed and no skipping) in order are
%     A0,B0,C0,D0,E0,F0,k1,k2,k3,k4,k5,t_end,savefig
% Returns a vector of times and an array of []'s of A, B, C, D, E, F
% Makes two plots, one large to show all []'s and one small to evaluate SSA
%     and rapid equilibrium approximations for D and F
% Typical call with default rate constants and initial concentrations:
%     [t,Y]= ABCDEFkin_2(1,.75,0,0,0,0,6,9,2,1,.1,5,0);
% This choice of k's demos a situation where the SSA applies to D and rapid eq between C and F
%     [t,Y]= ABCDEFkin_2(1,.75,0,0,0,0,6,9,200,1000,100,2,0);
% This shows a simple A + B -> C + D -> C + E and leaves off the savefig flag
%     [t,Y]= ABCDEFkin_2(1,1,0,0,0,0,6,0,2,0,0,2);
% Calls function ABCDEFdeltas (at the end of this file) to provide differential rates
% Calls function export_fig if and only if savefig flag is set to 1
%   Download export_fig from http://www.mathworks.com/matlabcentral/fileexchange/23629-exportfig
%
% Define rate constants and initial concentrations
% Defaults:

A ⇌ B ⇌ C Kinetics. Download AtoBtoCkin.m. Back to List. Browser version: A → B → C kinetics.

function [T1,Y1,fh] = AtoBtoCkin(varargin)

%AtoBtoCkin Simulates kinetics of the reaction scheme below via numerical
%  integration of differential rate laws
%  A <-> B <-> C
% Graphs concentrations of A, B, C and also shows how well the SSA applies to B
%  (graphs B with the assumption that it responds instantly to extant
%  concentrations of A, B, and C).
% The SSA works well when B decays much faster than A and C change,
%  even if [B] itself is not small (i.e. if B also builds up fast).
% Jason Kahn U Maryland 9/23/2026  version 1
% Arguments are all optional, but order is fixed, and no skipping except can enter []
% to keep default values. Arguments in order are
%      A0,B0,C0,k1,k2,k3,k4,t_end
%
% Returns a vector of times, an array of []'s of A, B, C, and a figure handle
%
% Example calls (args: A0,B0,C0,k1,k2,k3,k4,t_end; omit t_end or set it to 0 for auto)
%
% Rapid pre-equilibrium A<=>B, then slow irreversible B->C (biphasic)
%  AtoBtoCkin(1,0,0,20,30,1,0);
%  AtoBtoCkin(1,0,0,20,30,1,0,1);      % same, t_end = 1 to show the fast phase
%  AtoBtoCkin(1,0,0,5,3,0.05,0);      % very slow leak to C, strongly biphasic
%  AtoBtoCkin(1,0,0,5,3,0.05,0,1);    % same, fast phase only
%
% Irreversible or partly irreversible consecutive reactions
%  AtoBtoCkin(0.5,0,0,5,0,2,0);        % classic A->B->C: maximum in B, lag in C
%  AtoBtoCkin(1,0,0,5,2.5,2,0);        % reversible first step
%
% Fully reversible, comparable rate constants
%  AtoBtoCkin(1,0,0,5,1,5,1);
%
% Reactive intermediate: SSA for B improves as k2+k3 grows
%  AtoBtoCkin(1,0,0,5,20,20,1);
%  AtoBtoCkin(1,0,0,5,50,50,1);
%  AtoBtoCkin(1,0,0,50,20,20,0.);      % fast B formation too: SSA marginal
%
% Nonzero starting B and C
%  AtoBtoCkin(1,.50,.10,5,1,6,2);
%  AtoBtoCkin(1,.50,.10,5,10,60,2);    % B starts far above steady state: fast transient
%  AtoBtoCkin(0,.50,.40,5,10,60,12);  % no A at start: A forms by back reaction
%
% Slow irreversible A->B feeding faster B<=>C
%  AtoBtoCkin(1,0,0,0.5,0,5,1);
%
% A<=>B only (k3 = 0, so C never forms)
%  AtoBtoCkin(1,0,0,5,0.4,0);
%
% Calls function ABCdeltas (at the end of this file) to provide differential rates
%
% Used Claude to decide on t_end using the eigenvalues of the rate matrix
%

Microstates and Configurations Animation. Download zip file. Back to List. The zip file includes several other necessary routines, but you will need to download the partitions function from the Matlab file exchange as described above.

function [ W ] = micro_mov_r3(varargin)

function outstruct = micro_movr3(varargin)
% Usage: outputstructure = micro_movr3(quanta,particles,pcflag,toppc,nodispflag,inputstructure);
% Illustrates and animates configurations and microstates for a toy model
% of distributing energy among particles, inspired by Nash's ChemThermo
% and equal to a 1-D simplified version of the Einstein model for a solid.
% Calculates W, T, S, and other results.
% Direct enumeration is SLOW for big q and p numbers! Set the nodispflag
% flag to 1 to forego looking at individual configurations and simply
% output values calculated from the Einstein solid model formulae.
% Arguments: micro_movr3(quanta,particles,pcflag,nodispflag,inputstructure,toppc);
% All arguments are optional but must be given in order if uses, some
% conflict with each other.
% Default >> micro_movr3 is equivalent to >> micro_movr3(3,5,'',8,0,'');
% Set quanta and particles and allow animations as in micro_movr3(6,8);
% set pcflag to 'pc' to show only predominant configurations, as in
% micro_movr3(13,20,'pc');
% set toppc to change the number of configurations displayed and averaged
% over in 'pc' view (default toppc = 8). Takes a numerical argument
% (e.g. 8, 15, 31, 6n-1 for n >= 6) as in
% res3 = micro_movr3(17,24,'pc',15,'',''); Toppc does nothing in
% animation mode, but if p and q are too large and the program goes
% into pc mode it will use the value of toppc. So for example
% micro_movr3(17,24,'',15,'',''); will give the same result.
% set nodispflag = 0 or omit or enter [] to allow animations if possible
% set nodispflag = 1 to just get a calculation of W, S, N0, and T as in
% micro_movr3(47,20,'',1). If nodispflag is 1, then we still try count the
% total number of configurations rather than enumerating each of them,
% but we do not generate graphs of configurations, so nodispflag = 1
% overrides 'pc' or '' in the previous argument.
% Set nodispflag = 2 to get a plot of one representative predominant
% configuration. This routine assumes the Boltzmann dsitribution is
% true and calculates a configuration that is usually very close to the
% most populated. Works for very large numbers of quanta and particles.
% If desired, could add more logic that uses the actual value of nodsipflag.
% set inputstructure to be the result structure (outstruct) from a previous
% run, to save time by reusing a partition list (qlist) under some conditions
% res1 = micro_movr3(17,20,'',0); % But note if nodispflag is set to 1 here,
% there will be no qlist generated
% res2 = micro_movr3(17,24,'',0,res1); % This will find and re-use the
% qlist from the res1 structure, if it still exists
% (RFE : the partition list generation is the slowest step. Should filter
% it and write out qlists for all smaller problems. All of the configs for
% q = 50 and p = 30 are contained in the q = 50 and p = 40 list. So for
% every q,p that the user enters could just generate ql's for all smaller
% values of p. Somehow they have to get stored for re-use, which would be
% a very large file)
% RFE implement an absolutely no plots output for use within scripts. For
% now, be careful to close plots after making them or the system will bog
% down.
% Jason Kahn U Maryland 4/3/2019 version 1.3
% outputs a structure with the following fields
% outstruct.q quanta
% outstruct.p particles
% outstruct.Wd # of microstates - direct calc
% outstruct.Sd entropy - direct calc
% outstruct.NCd # of configurations - direct calc
% outstruct.N0d direct count of particles with zero energy
% outstruct.Td T from the fit to an exponential to direct calc occupancies
% outstruct.WE # of microstates - from Einstein solid (p+q-1)!/[(p-1)!q!]
% outstruct.SE entropy - from Einstein solid model
% outstruct.NCE # of configurations from integer partition function
% outstruct.N0E # of particles with zero energy in the ensemble - from
% the area of an exponential given known TE from the thermo dE/dS
% outstruct.TE T from from the thermodynamic (1/T) = dE/dS
% outstruct.ql the qlist, the list of configurations, is provided if q < p
% for possible use in a subsequent calculation, otherwise it is 0
%
% micro_movr3 calls JDK's functions placequanta, calcdist, partitionnum, partitionnumrec,
% partitionfct, pentagonalnums, and RoundSum -- they must all be in the path as well
% Also requires "partitions" function from the Matlab File Exchange:
% This one: http://www.mathworks.com/matlabcentral/fileexchange/
% 12009-partitions-of-an-integer
% Try/catches to use cprintf if it is available.
% Shows all of the configs and microstates for "quanta" units of energy
% randomly allocated into "particles" boxes.
% Animations pause often -- hit spacebar in the plot window to continue, if you hit
% the spacebar too many times will bring the front window back and you
% may need to bring plot window to the front again to continue. You
% can always control-C out from the command window.
% Can generate a lot of plots -- get rid of them with "close all"
% Caution: We are counting microstates! Will take forever for large
% numbers of particles! You're asking for trouble if you enumerate
% when either quanta or particles is > 50. In this case the program
% may decide to take shortcuts on its own.
% For just calculating W, uses expression for the Einsten model of a solid:
% Weinsolid = factorial(particles+quanta-1)/(factorial(quanta)*factorial(particles-1));
% which will be non-infinite for particles+quanta-1 < 171, otherwise
% uses some tricks to avoid evaluating the factorial and still gives W, or just
% uses the gammaln function gammaln(n) = log(factorial(n-1)) to report
% just the entropy, proportional to ln(W).
% T is in units of the Einstein Temperature (ThetaT). T is thus 1/(the exp
% decay constant) from the Boltzmann distribution.

Coin flipping illustrates the predominant configuration. Download zip file. Back to List.

function normy = nflips2

% Plots the probability of x% of Z coin tosses coming up heads
% Uses one array of Z for discrete calculations (discz) and
% one for only a continuous approximation (zgam)
% Jason Kahn U Maryland 4/20/2016 version 1.01
% Some plots are scaled to max probability ("normalized")
% Probability(H) = (Z!)/[(H!)(T!)]
% ln(P) = ln(Z!) - ln(H!) - ln((Z-H)!)
% The gamma function generalizes the factorial Gamma(X) = (X-1)!
% Could rewrite to take these arrays as arguments...

Maxwell-Boltzmann Distribution. Download zip file. Back to List.

% Mbdist_vs_mass.m script
% Script for showing the Maxwell-Boltzmann distribution for different masses
% Jason Kahn U Maryland 2/25/2016  version 1.01
% Edit the three vectors below to control illustration.
% Clumsy; should rewrite for arbitrary number of masses, and pre-compute
% maximum velocities and kinetic energies for optimal scaling
% Calls the createMBfig function to give the distributions.
% Makes two plots, one vs v and one vs K.E.

function [v,probv,vdots,pdots,figure1] = createMBfig(molwt,Tvec,maxv,verts)

% Example: [v,probv,vdots,pdots,fig1] = createMBfig(20,100:50:300,1500,1);
% Jason Kahn U Maryland 2/25/2016  version 1.01
% All arguments are required. Plain argon at RT would be createMBfig(40,298,1000,0);
% Plots Maxwell-Boltzmann distributions for P(v) vs. v for a particle
% of mass molwt, at temperatures given in Tvec, up to maximum velocity maxv
% If verts = 1 plots vertical lines for most common, average, and rms
% velocities. Returns matrices of v's and P(v)'s, and the most common
% values, and figure handles (so calling functions can delete the plot)
% Jason Kahn, 11/10/09 - modified January 2016

LeChatelier’s Principle Illustration. Download Sim_twoAtoBr3.m. It also needs the two helper functions shown below: TwoAtoB.m and A2Brates.m. The older version, Sim_twoAtoBr2, with its helpers: Download zip file. Back to List. Browser version: Le Chatelier’s principle and Q going to K.

function [T,Y,ctr] = Sim_twoAtoBr3(varargin)

% Function to illustrate LeChatelier's principle and dynamic equilibrium by
%    simulating the gas phase dimerization reaction 2 A(g) <-> B(g)
%    as a function of time, with a change in volume, change in P(A), change
%    in P(B), and return to original volume to illustrate induced changes
%    in the rxn quotient Q and its reversion to Kp.
% (To do the expt one would need magical non-interconverting tanks of A and B
%    plus the ability to remove one or both instantly and/or do rapid
%    expansion and compression whilst remaining at constant T. Details, details.)
% Jason Kahn U Maryland 2/26/2025  version 1.3 (renamed Sim_twoAtoBr3)
% Returns a time vector and concentration matrix, for example if one wanted
%    to replot to compare different rate constants etc.
% Integrates differential rate law, plots pressures, rates, and Q vs. K
% Nine Arguments (all optional) must be in the following order:
% kf,kr,A0,B0,deltaA,deltaB,volume change ratio (compression for >1),
%    ....set relaxation time (0 for let it be calculated),savefig flag
% You can leave arguments off at the end but no skipping.
% With no arguments defaults to: Sim_twoAtoBr3(3e-2,6e-2,1,4,5,5,2,0,0);
% To just display dynamic equilibrium with no compressions or additions
%  use e.g. Sim_twoAtoBr3(6e-2,20e-2,4,8,0,0,1,0,0);
% Calls function TwoAtoB (provided separately) to calculate differential
%  rates that are then integrated using ode45
% Calls function A2Brates (provided separately) to regenerate rates for
%  plotting purposes
% Calls function export_fig if and only if savefig flag is set to 1
%  Download export_fig from
% Note that the injections or magical removals of A and B are spec'd in
%  terms of partial pressures at the compressed/expanded volume, so e.g.
%  equal initial P(A) and added P(A) represent different numbers of moles.
% The total partial pressure at the end may exceed that at the beginning.
% And of course A and B behave as ideal gases
%
% To output plots will require
% https://www.mathworks.com/matlabcentral/fileexchange/23629-export_fig
% or there is a GitHub repository for it
%

The older version, in the zip file:

function [T,Y] = Sim_twoAtoBr2(varargin)

% Usage: Sim_twoAtoBr2(kf,kr,A0,B0,deltaA,deltaB,Vratio,t_end_set,saveflag)
% as in >> Sim_twoAtoBr2(3e-2,6e-2,1,4,5,5,2,0,0); % defaults
% Function to illustrate LeChatelier's principle and dynamic equilibrium by
% simulating the gas phase dimerization reaction 2 A(g) <-> B(g)
% as a function of time, with a change in volume, change in P(A), change
% in P(B), and return to original volume to illustrate induced changes
% in the rxn quotient Q and its reversion to Kp.
% Jason Kahn U Maryland 11/8/2016 version 1.3
% Change log -- 1.3 cosmetics, checked capitalization of function names
% 1.2 (r2) calculation of relaxation times to make plots
% look good
% 1.01 first version provided
% Returns a time vector and concentration matrix, although not sure what
% one would do with the returned values.
% Integrates differential rate law, plots pressures, rates, and Q vs. K
% Arguments (all optional) must be in the following order:
% kf,kr,A0,B0,deltaA,deltaB,volume change ratio (compression for >1),
% ....set relaxation time (0 for leave alone),savefig flag
% You can leave arguments off at the end but no skipping.
% With no arguments defaults to: Sim_twoAtoBr2(3e-2,6e-2,1,4,5,5,2,0,0);
% Calls function TwoAtoB (provided separately) to calculate differential
% rates that are then integrated using ode45
% Calls function A2Brates (provided separately) to regenerate rates for
% plotting purposes
% Calls function export_fig if and only if savefig flag is set to 1
% Download export_fig from http://www.mathworks.com/matlabcentral/fileexchange/23629-exportfig
%
% Define rate constants and initial partial pressures
% Defaults:

% Differential rate law for change in concs given kf and kr for 2A <-> B
% Jason Kahn U Maryland 2/25/2016  version 1.01

function dconcs = TwoAtoB(~,concs,kf,kr)
dconcs = zeros(2,1);
dconcs(1) = -2*kf*concs(1)^2 + 2*kr*concs(2);
dconcs(2) = kf*concs(1)^2 - kr*concs(2);
end

% Function provides differential rates for 2A <-> B, called by Sim_twoAtoB
% Jason Kahn U Maryland 2/25/2016  version 1.01
function A2Brates = A2Brates(concs,kf,kr)
A2Brates(1) = kf*concs(1)^2;
A2Brates(2) = kr*concs(2);
end

Michaelis-Menten Kinetics Programs and Scripts. Download zip file. Back to List.

% This is the MMgraph_scr.m script for illustrating progressively more
%   realistic enzymatic reactions.
% Jason Kahn U Maryland 2/25/2016 version 1.01
% The top row of plots is the overall reaction,
% the bottom is initial rates. It starts with pure ideal M-M kinetics,
%   then looks at the effects of product inhibition, then reversible reactions.
% All assuming steady state MM kinetics at small [E] so E does not titrate out S or P
% This is a script rather than a function to allow fiddling with all inputs
%   as desired. Calls RevMicMen(S0,P0,KmS,KmP,Keq,VmaxS,Tf), which
%   integrates under steady-state conditions.
% Print nice output with e.g. export_fig -m3 ~/Desktop/mmkin2.png if you
% have downloaded the nice export_fig from the File Exchange.
% The figure handle is returned in fig1 so export_fig(fig1, filename);
% Note this is very kludgy and options are changed throughout below!

function [ t,concs ] = RevMicMen(S0,P0,KmS,KmP,Keq,VmaxS,Tf)

% RevMicMen Calculates time courses from M-M kinetic parameters
% Jason Kahn U Maryland 2/25/2016  version 1.01
%   Outputs concs = S and P concentrations as column vectors of one matrix,
%   vs. time as a column vector
%   Typical Usage: RevMicMen(1e-4,0,1e-5,1e-3,10,10e-5,2.5);
%   By Briggs-Haldane, VmaxR = (VmaxF*KmR)/(Keq*KmF) so it is not specified
%       intependently.
%   Program integrates vf = ([S] - [P]/Keq)*(Vmaxf/(KmS + [S] + [P]*KmS/KmP))
%   See http://www.mathworks.com/help/matlab/math/ordinary-differential-equations.html
%   Syntax is [t,y] = solver(odefun,tspan,y0,options)

function [T,Y] = MMkinetics(varargin)

% Function to simulate Michaelis-Menten enzyme kinetics as a function of time,
%   assuming irreversible conversion of S to P and no product inhibition
% Jason Kahn U Maryland 2/25/2016  version 1.01
% Plots results in 6 plots comparing steady-state and pre-steady state time scales
% Arguments (all optional) must be in the following order: k1,kr1,kcat,S0,E0,t_end,savefig flag
% You can leave arguments off at the end but no skipping.
% With no arguments defaults to: MMkinetics(5e6,6e4,300,0.1,1e-5,74.7,0);
% Returns an array of times and []'s of Efree, ES, S, and P
% Calls function MMkin to provide differential rates and to regenerate rates for plotting purposes
% Calls function export_fig if and only if savefig flag is set to 1
%   Download export_fig from http://www.mathworks.com/matlabcentral/fileexchange/23629-exportfig

function dconcs = MMkin(~,concs,k1,kr1,kcat)

% Calculate the change in concentration of Efree, ES, S, and P
% Returns the change in each concentration
% Jason Kahn U Maryland 2/25/2016  version 1.01
% These deltas are integrated in the calling program.
% Assumes initial rate conditions -- no product inhibition

function [S0vector,v0,figure1] = MM_inhib(varargin)

% Usage [S0,vs,figh] = MM_inhib(Ivector,Km,KI,KIprime,Vmax,S0vector);
%   or just MM_inhib to use defaults
% Jason Kahn U Maryland 2/25/2016  version 1.01
% All arguments are optional but must be given in order
% Graphs v0 vs. [S] for each [I], and also the Lineweaver-Burke plots
% Returns S0vector, the matrix of v0 vs. S for each [I],and the figure
% handle in case you want to export it or close it.
% Assumes initial rate conditions, so no point showing a time course.
% Assumes [E] << Km and KI and KIprime so can't titrate out I
% In the workspace, can define S0vector as for example
% >> S0 = [0.05 0.07 0.1 0.3 0.5 0.75 1 1.25 1.5 2 3.5 5 7 10];
% and Ivector as >> Ivector = [0 1e-6 3e-6 1e-5 5e-5 1e-4 ];
% Defaults to MM_inhib(Ivector,2e-5,1e-5,100,6e-3,S0);
% Change the S0vector (in units of Km) to explore different ranges of [S]
% Set defaults: