Fit SimBiology model parameters to data (requires SimBiology and Statistics and Machine Learning Toolbox) — fitproblem, sbiofit, population PK NLME, covariate models, virtual patients, confidence intervals, and NCA. Use when asked to fit, estimate, or calibrate a SimBiology model or PK/PD model against measured concentration-time data, or to compute PK metrics such as AUC, Cmax, half-life, or clearance.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Simbiology Fit Model?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/matlab-simbiology-fit-model)
---
name: simbiology-fit-model
description: "Fit SimBiology model parameters to data (requires SimBiology and Statistics and Machine Learning Toolbox) — fitproblem, sbiofit, population PK NLME, covariate models, virtual patients, confidence intervals, and NCA. Use when asked to fit, estimate, or calibrate a SimBiology model or PK/PD model against measured concentration-time data, or to compute PK metrics such as AUC, Cmax, half-life, or clearance."
license: https://www.mathworks.com/content/dam/mathworks/license/pmrl/license.md
metadata:
author: MathWorks
version: "2.1"
---
# Fit SimBiology Models
Estimate parameters from data using `fitproblem`, fit population models
with NLME, generate virtual patients, and compute NCA metrics.
## When to Use
- "fit", "estimate", "calibrate" model parameters
- Parameter estimation from experimental/observed data
- Population PK/PD, NLME, mixed effects, inter-individual variability
- Virtual patients, virtual cohorts
- NCA, AUC, Cmax, Tmax, half-life, clearance
- Keywords: "fit", "estimate", "calibrate", "population", "NCA", "AUC"
## When NOT to Use
- Model construction or diagram (use `simbiology-build-model`)
- Simulation without fitting (use `simbiology-simulate-model`)
- Sensitivity analysis (use `simbiology-simulate-model`)
## Must-Follow Rules
### 1. Use `fitproblem` for parameter estimation
Always use `fitproblem` instead of calling `sbiofit` or `sbiofitmixed`
directly. `fitproblem` provides a unified, declarative interface:
```matlab
prob = fitproblem;
prob.Model = model;
prob.Data = data;
prob.ResponseMap = "Species = DataColumn";
prob.Estimated = estimatedInfo({'param'}, 'Bounds', [lo hi]);
results = fit(prob);
```
Do NOT call `sbiofit(model, data, ...)` or `sbiofitmixed(model, data, ...)`
directly — their positional argument signatures are error-prone.
### 2. Use `groupedData` with explicit variable names
`fitproblem` auto-converts a plain table but guesses the column roles
(direct `sbiofit` rejects tables). Wrap data and set names explicitly:
```matlab
data = groupedData(table(...));
data.Properties.IndependentVariableName = 'Time';
```
### 3. `ResponseMap` maps model outputs to data columns
Format is always `"ModelOutput = DataColumnName"`:
```matlab
% Single compartment — use species name on the left
prob.ResponseMap = "Drug = DrugConc";
% Multi-compartment — use qualified name to disambiguate
prob.ResponseMap = "Central.Drug = DrugConc";
% When species name matches data column name, still use the = format
prob.ResponseMap = "Drug = Drug";
```
Use the unqualified species name unless the same species name exists
in multiple compartments (then qualify with `Compartment.Species`).
For hierarchical models with submodels, use the fully qualified name from
the root, in `estimatedInfo` too: `"Top.Sub.Compartment.Species = DataColumn"`,
`estimatedInfo("Top.Sub.k")`. Names without the root model are rejected.
If the mapped output is an observable that references constant parameters or
compartments (e.g. `Drug ./ Vd`), log them before fitting, or the fit stops with an error that they aren't logged:
`cs.RuntimeOptions.StatesToLog = [m.Species; m.Compartments; sbioselect(m,'Type','parameter','Constant',true)];`
### 4. Always set bounds
Prevent non-physical values (negative rates, etc.):
```matlab
estimParams = estimatedInfo({'ke','ka'}, ...
'InitialValue', [0.2, 1.0], ...
'Bounds', [0.01 1; 0.1 5]);
```
### 5. Use log transform for rate constants
Parameters spanning orders of magnitude (clearances, rate constants)
benefit from log-transform estimation. Set `.Transform` after creation:
```matlab
ei = estimatedInfo({'ke','ka'}, 'InitialValue', [0.1, 0.5], 'Bounds', [0.01 1; 0.1 5]);
ei(1).Transform = 'log';
ei(2).Transform = 'log';
```
Alternative: use `'log(param)'` name syntax (equivalent result):
```matlab
ei = estimatedInfo({'log(ke)','log(ka)'}, 'InitialValue', [0.1, 0.5], 'Bounds', [0.01 1; 0.1 5]);
```
**Important:** `InitialValue` and `Bounds` are always in the
**untransformed** (natural) domain. Do NOT pass `log(value)`.
Available transforms: `'log'`, `'logit'`, `'probit'`
Do NOT pass `'Transform'` as a name-value pair to the `estimatedInfo`
constructor — it errors. Always set the `.Transform` property after.
### 6. Error models for population fitting
Choose the error model that matches the noise structure:
- `'constant'` — absolute noise uniform
- `'proportional'` — noise scales with magnitude (most PK data)
- `'combined'` — both constant and proportional
- `'exponential'` — log-normal residual
### 7. NCA requires `sbioncaoptions` object
Do not use name-value pairs. Column names are camelCase.
Put the dose only on dosing rows (`NaN` or 0 elsewhere). A dose on every
row is read as repeated dosing.
## Decision Table
| Scenario | Approach |
|----------|----------|
| Single subject or pooled fit | `fitproblem` with `FitFunction="sbiofit"`, `Pooled=true` for multi-subject data |
| Individual fits per subject | `fitproblem` with `Pooled=false` (or default `"auto"`) |
| Population NLME (IIV, random effects) | `fitproblem` with `FitFunction="sbiofitmixed"` |
| Model-independent PK metrics | `sbionca` |
## `fitproblem` Workflow (Preferred)
Use `fitproblem` for all parameter estimation. It provides a unified,
declarative interface that replaces direct calls to `sbiofit`/`sbiofitmixed`:
```matlab
% 1. Prepare data
data = groupedData(table(tSample, yData, 'VariableNames', {'Time','Drug'}));
data.Properties.IndependentVariableName = 'Time';
% 2. Define parameters with bounds
estimParams = estimatedInfo({'ke','ka'}, ...
'InitialValue', [0.2, 1.0], ...
'Bounds', [0.01 1; 0.1 5]);
% 3. Build the fit problem
prob = fitproblem;
prob.Model = model;
prob.Data = data;
prob.ResponseMap = "Drug = Drug";
prob.Estimated = estimParams;
prob.Doses = dose; % optional
% FunctionName defaults to "auto" (local); use 'scattersearch' if the fit stalls
% 4. Fit
results = fit(prob);
% 5. Inspect
disp(results.ParameterEstimates);
plot(results);
```
### Key `fitproblem` properties
| Property | Purpose |
|----------|---------|
| `Model` | The SimBiology model object |
| `Data` | `groupedData` table |
| `Estimated` | `estimatedInfo` object (**not** `EstimatedParameters`) |
| `ResponseMap` | Maps model species to data columns |
| `Doses` | Dose object(s) (**not** `Dose`) |
| `FitFunction` | `"sbiofit"` (default) or `"sbiofitmixed"` |
| `FunctionName` | Algorithm: `"auto"` (default: `lsqnonlin` with Optimization Toolbox, else `nlinfit`), `'scattersearch'`, `'nlinfit'`, `'fminsearch'`, `'lsqnonlin'`, `'particleswarm'`; with `sbiofitmixed`: `'nlmefit'` or `'nlmefitsa'` (SAEM). nlinfit fits can't give `ProfileLikelihood` CIs, so set `'lsqnonlin'` or `'fminsearch'` when you need them. Check the toolbox with `exist("lsqnonlin")`, not `license` |
| `ProgressPlot` | `true` to show live fitting progress |
| `UseParallel` | `"auto"` (pool if available) or `"on"` (require pool) — R2026b+; `true`/`false` still works but not recommended, and is the only form R2026a accepts |
| `Pooled` | `true`/`false`/`"auto"` (default, sbiofit only). `"auto"` fits each group separately unless `CategoryVariableName` is set |
| `ErrorModel` | `"constant"`, `"proportional"`, `"combined"`, `"exponential"` |
| `Variants` | Variants to apply during fitting. A groups-by-variants matrix sets per-group values, e.g. dose levels given through a parameter |
**Common property name mistakes:** `prob.Estimated` (not `EstimatedParameters`),
`prob.Doses` (not `Dose`), `prob.FunctionName` (not `Algorithm` or `Method`).
### Estimation algorithms
| Method | Use Case |
|--------|----------|
| `'scattersearch'` | Built-in global search, no extra toolbox — use when a local fit stalls or depends on the start point |
| `'nlinfit'` | Local; smooth problems (the `"auto"` choice without Optimization Toolbox) |
| `'lsqnonlin'` | Bounded least squares (Optimization Toolbox) |
| `'fminsearch'` | Derivative-free, simple problems |
| `'particleswarm'` | Global search (Global Optimization Toolbox) |
### Dosing from multi-subject data
When subjects receive different doses, use `createDoses` to extract
per-subject dose objects from the data. The dose column must have `NaN`
(or 0) on non-dosing rows:
```matlab
% Data format: dose amount only at administration time, NaN elsewhere
% ID Time Dose DrugConc Group
% 1 0 50 0 LowDose
% 1 1 NaN 2.05 LowDose
% ...
% 3 0 200 0 HighDose
% Create template dose targeting the depot species
tempDose = sbiodose('StudyDose');
tempDose.TargetName = 'Depot.Drug'; % match your model's dose target
% Extract per-subject doses from groupedData
doseArray = createDoses(gData, 'Dose', '', tempDose);
% Pass to fitproblem
prob.Doses = doseArray;
```
**Critical:** If all rows have the dose value (not just dosing times),
`createDoses` will treat every row as a dose event. Use `NaN` on
non-dosing rows.
### Population fitting (pooled vs individual)
```matlab
data.Properties.GroupVariableName = 'SubjectID';
% Pooled — one parameter set for all
prob.Pooled = true;
% Individual — separate per subject (also the default "auto" for multi-group data)
prob.Pooled = false;
results = fit(prob); % results is an array, one per group: use results(i)
```
### Category-based pooling (per-group estimates)
To estimate parameters separately per category (e.g., dose group), use
`CategoryVariableName` on the `estimatedInfo` object — **not** on
`fitproblem` or `sbiofit`:
```matlab
estimParams = estimatedInfo({'ke'}, 'InitialValue', 0.1, 'Bounds', [0.01 1]);
estimParams.CategoryVariableName = 'DoseGroup'; % column in data table
prob.Estimated = estimParams;
% Do NOT set prob.Pooled — leave it at the default
results = fit(prob);
% ParameterEstimates has one row per SUBJECT; collapse to one per category:
unique(results.ParameterEstimates(:, {'CategoryValue','Estimate'}))
```
**Warning:** Do NOT set `prob.Pooled` when using `CategoryVariableName`.
Setting `Pooled` to either `true` or `false` **ignores**
`CategoryVariableName` (MATLAB issues a warning). Leave `Pooled` at
`"auto"` to let the category-based pooling work correctly.
## NLME Population Fitting
For inter-individual variability and random effects estimation,
set `FitFunction` to `"sbiofitmixed"`. Don't set `prob.Options` to a `statset`:
both `nlmefit` and `nlmefitsa` reject it. A default SAEM run takes minutes. To
shorten it, pass `nlmefitsa` options as a struct:
`prob.Options = struct('NIterations', [50 50 25]);` (125 iterations instead of 400).
```matlab
% 1. Load & tag grouped data
data = groupedData(readtable('pop_pk_data.csv'));
data.Properties.IndependentVariableName = 'Time';
data.Properties.GroupVariableName = 'SubjectID';
% 2. Define parameters (Bounds ignored by sbiofitmixed — use InitialValue only)
estimParams = estimatedInfo({'CL','Vd','ka'}, ...
'InitialValue', [5, 50, 1.2]);
% 3. Build the fit problem
prob = fitproblem;
prob.Model = model;
prob.Data = data;
prob.ResponseMap = "DrugConc = Concentration";
prob.Estimated = estimParams;
prob.FitFunction = "sbiofitmixed";
prob.ErrorModel = "proportional";
% 4. Fit
results = fit(prob);
% 5. Inspect
results.FixedEffects
results.RandomEffectCovarianceMatrix
results.IndividualParameterEstimates
results.ErrorModelInfo % table: ErrorModel, a, b per response
```
### When to use NLME vs sbiofit
| Criterion | `FitFunction="sbiofit"` | `FitFunction="sbiofitmixed"` |
|-----------|-----------|----------------|
| Single subject | Yes | |
| Multiple subjects, no IIV | Yes (pooled) | |
| Inter-individual variability | | Yes |
| Random effects estimation | | Yes |
| Covariate modeling | | Yes |
| Small datasets (< 5 subjects) | Yes | May not converge |
| Bounds on parameters | Yes (enforced) | **Ignored** — use good InitialValue instead |
### NLME with covariates (CovariateModel)
When covariates (e.g., weight, age) influence parameters, use a
`CovariateModel` instead of `estimatedInfo`:
```matlab
% 1. Define covariate-parameter relationships
covModel = CovariateModel;
covModel.Expression = {
'CL = theta1 + theta2*WT + eta1'
'Vd = theta3 + theta4*WT + eta2'
'ka = theta5 + eta3'
};
% 2. Set initial fixed effect values
initVals = covModel.constructDefaultFixedEffectValues;
initVals.theta1 = 5; % baseline CL
initVals.theta2 = 0.1; % WT effect on CL
initVals.theta3 = 50; % baseline Vd
initVals.theta4 = 0.5; % WT effect on Vd
initVals.theta5 = 1.2; % ka
covModel.FixedEffectValues = initVals;
% 3. Build fit problem (set FitFunction BEFORE Estimated to avoid warning)
prob = fitproblem;
prob.Model = model;
prob.Data = data; % groupedData with WT column
prob.ResponseMap = "DrugConc = Concentration";
prob.FitFunction = "sbiofitmixed";
prob.Estimated = covModel; % CovariateModel instead of estimatedInfo
prob.ErrorModel = "proportional";
% 4. Fit and inspect
results = fit(prob);
results.FixedEffects
results.RandomEffectCovarianceMatrix
```
**When to use which:**
- `estimatedInfo` — NLME without covariates (simpler, fewer parameters)
- `CovariateModel` — NLME with covariates (only way to express parameter-covariate relationships)
**Expression rules:**
- Every covariate term needs its own theta; numeric coefficients are rejected at fit time. Allometric power law: `'CL = exp(theta1 + theta2*log(WT/70) + eta1)'` (typical CL at 70 kg is `exp(theta1)`; the exponent is estimated)
- A parameter the data needs but the model lacks (e.g. `CL` when the model uses `ke`): add it and a `repeatedAssignment` rule such as `ke = CL / Vd`. The rule target needs `Constant = false`: `p = sbioselect(m, 'Name', 'ke'); p.Constant = false;` (assigning through the `sbioselect` call errors)
- `theta` prefix for fixed effects, `eta` for random effects
- One random effect maximum per expression
- Use `verify(covModel)` to validate syntax before fitting. It takes only the covariate model, not the data
## Virtual Patient Generation
### From assumed distributions (Scenarios)
Use `SimBiology.Scenarios` with `makedist`. See "Virtual population via
distribution sampling" in `simbiology-simulate-model` (set `sc.RandomSeed`).
### From NLME results (sbiosampleparameters)
Use `sbiosampleparameters` to sample from fitted population parameters.
It applies the covariate expressions but does not infer covariate values.
```matlab
% Extract from NLME results
covModel = covariateModel(nlmeResults);
fe = nlmeResults.FixedEffects; % long table (Name, Estimate, ...); needs one row
thetas = array2table(fe.Estimate', 'VariableNames', fe.Name');
omega = nlmeResults.RandomEffectCovarianceMatrix;
% Sample 200 virtual patients. A scalar count works only when the expressions have no covariates.
nVP = 200;
vpParams = sbiosampleparameters(covModel.Expression, thetas, omega, nVP); % matrix, columns in covModel.ParameterNames order
% (a 2nd output is a CovariateModel, not names)
% With covariates (e.g. WT), pass one row per virtual patient instead of the count
vpCov = table((1:nVP)', 70*exp(0.2*randn(nVP, 1)), 'VariableNames', {'ID', 'WT'});
vpParams = sbiosampleparameters(covModel.Expression, thetas, omega, vpCov);
% Simulate (parameter order must match covModel.ParameterNames)
simfun = createSimFunction(model, covModel.ParameterNames, {'Cp'}, []);
vpSim = simfun(vpParams, 48);
```
## Non-Compartmental Analysis (NCA)
Use `sbioncaoptions` + `sbionca`. Key points:
- Set explicit `OutputTimes` for sufficient resolution near Cmax
- When simulating NCA data from a model, first remove or zero any stored doses, initial amounts and input reactions so only the intended dose drives the profile
- Column names are camelCase; dose only on dosing rows
- Metric names use underscores: `C_max`, `AUC_0_last`, `T_half`, `CL`, `V_z`, `MRT`
- Route comes from which dose column is set (`EVDoseColumnName` or `IVDoseColumnName`, plus `infusionRateColumnName` for infusion)
- Multi-subject: set `groupColumnName` on options. The output group column is categorical: `nca.CL(nca.Subject == "1")`
- Steady state: needs every dose row, plus `TAU`; see the NCA reference
See `references/nca-analysis-guidance.md` for full patterns.
## Confidence Intervals
`sbioparameterci` only works with `sbiofit` results (NOT `sbiofitmixed`).
```matlab
ciResults = sbioparameterci(fitResults); % Gaussian (fast)
ciPL = sbioparameterci(fitResults, 'Type', 'ProfileLikelihood'); % better for nonlinear
plot(ciPL);
```
| Type | Use when |
|------|----------|
| `'Gaussian'` (default) | Quick check, well-behaved problems |
| `'ProfileLikelihood'` | Final results, parameter identifiability |
`.Results` table columns: `Name` (cell), `ConfidenceInterval` (Nx2 double), `Status` (categorical).
There is no profile-data property (only `.Results` and `.ExitFlags`); view profiles with `plot(ciPL)`.
See `references/confidence-intervals-guidance.md` for options and column access patterns.
## Conventions
- **Species names must differ from compartment names.** SimBiology errors if a species shares the same name as its parent compartment (e.g., species `Depot` inside compartment `Depot`). Use distinct names: compartment `Depot` with species `DrugDepot`, or compartment `GI` with species `Drug`.
- **Units on compartment volumes:** If the model uses units, always specify units on compartment volumes too (e.g., `'liter'`). When compartment `Value` != 1 and units are inconsistent or missing, the fitting engine can produce Inf/NaN values. Also set `DimensionalAnalysis = true` in the configset and `VariableUnits` on the `groupedData` table (e.g., `data.Properties.VariableUnits = {'hour','milligram'}`). For pure amount-based models (no concentration), set compartment `Value = 1` and omit units.
- **Loading `.sbproj` files:** see "Model" in `simbiology-build-model` (struct fields are saved variable names, not model names)
- **Extracting simulation data for fitting:** Use `selectbyname` to get specific variables: `result = selectbyname(sbiosimulate(m), 'Drug'); drugVals = result.Data; t = result.Time;`. When sampling at specific times, use `resample`:
```matlab
sd = sbiosimulate(m);
[t, x, names] = resample(sd, tSample, 'linear');
```
- Start with the default local optimizer; switch to `'scattersearch'` if results depend on the initial values
- Use `'log'` transform for parameters spanning orders of magnitude (see Rule 5)
- Do NOT call `sbioaccelerate(model)` before fitting — it has no effect (fitting functions handle acceleration internally) and wastes time on unnecessary compilation
- Set `cs.MaximumWallClock = 60` before fitting — bad parameter guesses can make individual simulations hang; this configset property stops any single simulation exceeding the time limit
- Set `prob.ProgressPlot = true` only for long fits the user is watching (it opens a figure and slows fitting)
- Compute confidence intervals with `sbioparameterci` (see above)
## Evaluating Fit Quality
### Visual diagnostics
```matlab
plot(results); % observed vs predicted overlay
plotResiduals(results, 'time'); % type required: 'time', 'group', or 'predictions'
plotResidualDistribution(results); % histogram — should be ~normal
plotActualVersusPredicted(results); % identity line check
```
### Numeric metrics
```matlab
% sbiofit results (NLMEResults uses FixedEffects instead, and has no MSE)
results.ParameterEstimates % table: Name, Estimate, StandardError, Bounds
results.LogLikelihood % higher = better fit
results.AIC % lower = better (penalizes complexity)
results.BIC % lower = better (stronger complexity penalty)
results.MSE % mean squared error
```
### Model comparison
Compare competing models (e.g., one-compartment vs two-compartment) by BIC:
```matlab
results1 = fit(prob1); % simpler model
results2 = fit(prob2); % more complex model
deltaBIC = results2.BIC - results1.BIC;
% deltaBIC < -10: strong evidence for complex model
% deltaBIC > 0: simpler model preferred
```
### When to escalate to NLME
Consider `sbiofitmixed` (population fitting) when:
- Multiple subjects show similar trends but different parameter values
- Residuals show systematic subject-specific patterns
- You need to quantify inter-individual variability
- Covariates (weight, age) may explain parameter differences
- Pass **model objects** (not names) to fitting functions
- Do NOT call `sbiofit`/`sbiofitmixed` directly — use `fitproblem` (`sbionlinfit`, `sbionlmefit`, `sbionlmefitsa` and `sbioparamestim` were removed in R2026b; avoid them on R2026a too)
- **UseParallel (R2026b+):** Use `prob.UseParallel = "auto"` instead of `true` (R2026a: `true`/`false` only). Also applies to `sbioparameterci` and `sbiopredictionci`. `"on"` requires Parallel Computing Toolbox; `"auto"` falls back gracefully.
## References
Load on demand for detailed guidance:
- `references/nca-analysis-guidance.md` — full NCA patterns, IV infusion, metrics interpretation
- `references/confidence-intervals-guidance.md` — CI column access, profile likelihood options, prediction CIs
----
Copyright 2026 The MathWorks, Inc.
----