Skip to content
Back to skills

Matlab Analyze Bioinformatics Data

ASecurity

Use the MATLAB Bioinformatics Toolbox effectively for sequence analysis, NGS workflows, gene expression, and genomics. Use this skill when working with FASTQ/FASTA/BAM/SAM files, GTF annotations, BLAST searches or XML reports, read QC, trimming, filtering, RNA-Seq count tables and differential expression, sequence alignment, phylogenetics, mass spectrometry, microarray expression analysis, Gene Ontology, restriction enzymes, or sequence motifs, including choosing and configuring bioinformatic...

  • 1,414 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 5, 2026
ai-agentsgoexpressdebuggingdatabase

Security analysis

A100/100

Pro scans all 6 files and shows the line behind each finding

Scanned December 5, 2026

npx -y skills add matlab/matlab-agentic-toolkit --skill matlab-analyze-bioinformatics-data --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Matlab Analyze Bioinformatics Data?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Matlab Analyze Bioinformatics Data
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/matlab-matlab-analyze-bioinformatics-data/badge)](https://www.skillsdirectory.com/skills/matlab-matlab-analyze-bioinformatics-data)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: matlab-analyze-bioinformatics-data
description: >
  Use the MATLAB Bioinformatics Toolbox effectively for sequence analysis, NGS
  workflows, gene expression, and genomics. Use this skill when working with
  FASTQ/FASTA/BAM/SAM files, GTF annotations, BLAST searches or XML reports, read
  QC, trimming, filtering, RNA-Seq count tables and differential expression,
  sequence alignment, phylogenetics, mass spectrometry, microarray expression
  analysis, Gene Ontology, restriction enzymes, or sequence motifs, including
  choosing and configuring bioinformatics blocks in a pipeline (load alongside
  matlab-build-biopipeline). Guides toward purpose-built toolbox functions instead
  of building from scratch.
license: https://www.mathworks.com/content/dam/mathworks/license/pmrl/license.md
metadata:
  author: MathWorks
  version: "1.0"
---

# Bioinformatics Toolbox Expert

Use purpose-built Bioinformatics Toolbox functions instead of building from scratch with generic MATLAB. The toolbox provides tested, optimized implementations that handle edge cases (multi-mapping reads, dispersion estimation, variable-length quality strings) that manual code misses.

## When to Use

- Reading, writing, or processing FASTQ/FASTA/BAM/SAM files
- NGS read quality control, trimming, or filtering
- RNA-Seq differential expression analysis
- BLAST searches or parsing BLAST results
- Sequence alignment (pairwise or multiple)
- Phylogenetic tree construction
- Mass spectrometry peak detection and preprocessing
- Microarray normalization and differential expression
- Gene Ontology analysis
- Restriction enzyme analysis or sequence motifs
- Protein sequence analysis (cleavage, properties)
- RNA secondary structure prediction

## When NOT to Use

- General statistics unrelated to biological sequences
- Image processing of microscopy, gel, or microarray scan images (use `matlab-process-images`)
- Machine learning on non-sequence biological data
- Pipeline *mechanics* (block wiring, execution, debugging): use `matlab-build-biopipeline`, loaded alongside this skill. This skill still applies for choosing and configuring the blocks.

## Workflow

1. **Identify the biological task** — what is the user trying to accomplish?
2. **Choose the toolbox function** — consult the Key Functions table below
3. **Use file-level operations when available** — functions like `seqtrim`, `seqfilter`, and `featurecount` operate directly on files, avoiding manual parsing
4. **Run the code** with `evaluate_matlab_code`, or save it as a script and use `run_matlab_file`
5. **Verify results** — check output dimensions, plot QC metrics, confirm expected ranges

## Key Functions

### NGS Read QC & Preprocessing

| Function | Purpose | Since |
|----------|---------|-------|
| `seqqcplot` | Generate QC plots (quality boxplot, composition, GC/length distribution) from FASTQ | R2017a |
| `seqtrim` | Trim reads by quality (5 methods, sliding window support) | R2016b |
| `seqfilter` | Filter reads by quality/length (paired-end aware) | R2016b |
| `seqsplitpe` | Split merged (concatenated R1+R2) paired-end reads; not for interleaved files | R2016b |
| `fastqread` | Read FASTQ file into memory | — |
| `fastqwrite` | Write sequences to FASTQ file | — |
| `fastqinfo` | Get FASTQ file metadata without loading | — |

### RNA-Seq & Gene Expression

| Function | Purpose | Since |
|----------|---------|-------|
| `featurecount` | Count reads mapped to genomic features from BAM/SAM + GTF | R2016a |
| `rnaseqde` | Full DE analysis (negative binomial + FDR) in one call | R2021b |
| `nbintest` | Negative binomial test for count data (lower-level) | R2014b |
| `BioMap` | Structured access to BAM/SAM alignment data | — |
| `bamread` / `samread` | Read BAM/SAM files | — |
| `baminfo` / `saminfo` | Get alignment file metadata. `saminfo` has no `SequenceDictionary`; reference names need `saminfo(f, ScanDictionary=true).ScannedDictionary` | — |

### BLAST & Sequence Search

| Function | Purpose | Since |
|----------|---------|-------|
| `blastncbi` | Submit BLAST search to NCBI | — |
| `getblast` | Retrieve BLAST results (returns struct) | — |
| `blastread` | Parse saved single-query BLAST report files (multi-query XML reports are silently merged under the first query; split them per `<Iteration>` first) | — |

### Sequence Alignment & Phylogenetics

| Function | Purpose | Since |
|----------|---------|-------|
| `nwalign` | Needleman-Wunsch global alignment | — |
| `swalign` | Smith-Waterman local alignment | — |
| `multialign` | Progressive multiple sequence alignment | — |
| `seqpdist` | Pairwise distances for sequences | — |
| `seqlinkage` | Phylogenetic tree from distance matrix | — |
| `seqneighjoin` | Neighbor-joining tree | — |
| `phytree` | Phylogenetic tree object (view with `phytreeviewer`) | — |
| `seqdotplot` | Dot plot comparing two sequences | — |

Alignment to tree (DNA): `ma = multialign(seqs); D = seqpdist(ma, Method="Jukes-Cantor", Alphabet="NT"); tree = seqlinkage(D, "average", seqs);`

`nwalign`, `swalign`, and `seqpdist` assume protein (`Alphabet="AA"`) by default. On DNA they run without error but return protein scores and distances, so pass `Alphabet="NT"`. `seqpdist` accepts only `"NT"`: `"DNA"`, `"RNA"`, or `"nucleotide"` are silently treated as protein (`nwalign`/`swalign` accept `"DNA"`). `multialign` detects the alphabet itself. To translate mitochondrial DNA, pass `GeneticCode="Vertebrate Mitochondrial"` to `nt2aa`.

`"Jukes-Cantor"` and `"p-distance"` need only `Alphabet="NT"`; keep the default gap handling unless the user asks otherwise (`Indels="pairwise-del"` changes the distances). Nucleotide-only distances (`"Kimura"`, `"Tamura"`, `"Tajima-Nei"`, `"Hasegawa"`, `"Nei-Tamura"`) fail on real alignments unless you do all three steps; each missing step errors without naming the cause ("not available for amino acids", "cannot score gaps", or an `accumarray` error from ambiguous bases):

```matlab
seqs = fastaread("aligned.fasta");
for k = 1:numel(seqs)   % 1. mask ambiguous bases (N, R, Y, ...) as gaps
    s = upper(seqs(k).Sequence);
    s(~ismember(s, 'ACGT-')) = '-';
    seqs(k).Sequence = s;
end
D = seqpdist(seqs, Method="Kimura", Alphabet="NT", Indels="pairwise-del");   % 2. Alphabet (default "AA")  3. gap handling
```

### Mass Spectrometry

| Function | Purpose | Since |
|----------|---------|-------|
| `msbackadj` | Baseline correction | — |
| `mslowess` | Nonparametric smoothing preserving peaks | — |
| `mspeaks` | Peak detection (raw → centroid) | — |
| `msnorm` | Normalize spectra | — |
| `msalign` | Align peaks to reference | — |

### Microarray

| Function | Purpose | Since |
|----------|---------|-------|
| `quantilenorm` | Quantile normalization | — |
| `mainvarsetnorm` | Invariant set normalization | — |
| `mattest` | Two-sample t-test for microarray data | — |
| `mafdr` | FDR correction (Storey or BH) | — |
| `mavolcanoplot` | Volcano plot | — |
| `mairplot` | MA plot (intensity-ratio) | — |
| `maboxplot` | Box plot of microarray data | — |
| `genevarfilter` / `genelowvalfilter` / `geneentropyfilter` | Filter genes by variance, low values, entropy. Control spots (e.g. `LAMBDA`, `SS DNA`) can pass; drop them by name | — |

### RNA Structure

| Function | Purpose | Since |
|----------|---------|-------|
| `rnafold` | Predict minimum free energy RNA secondary structure | — |
| `rnaplot` | Plot RNA secondary structure | — |

### Sequence Motifs & Restriction Enzymes

| Function | Purpose | Since |
|----------|---------|-------|
| `seqlogo` | Sequence logo from alignment | — |
| `restrict` | Find restriction enzyme cut sites | — |
| `cleave` | In silico protein digestion | — |
| `palindromes` | Find palindromic sequences | — |

### Gene Ontology

| Function | Purpose | Since |
|----------|---------|-------|
| `geneont` | Load Gene Ontology database (class) | — |
| `goannotread` | Read GO annotation file | — |
| `getancestors` | Find ancestor terms (method on `geneont`) | — |
| `getdescendents` | Find descendant terms (method on `geneont`) | — |
| `getrelatives` | Find related terms (method on `geneont`) | — |
| `num2goid` | Convert numeric IDs to GO format | — |

## Patterns

### NGS QC: Visualize, Trim, Filter

Use `seqqcplot` → `seqtrim` → `seqfilter` instead of building manual quality matrices and trimming loops. These functions operate directly on FASTQ files.

```matlab
% Visualize quality before processing
seqqcplot("reads_R1.fastq", "QualityBoxplot");

% Trim 3' ends using sliding window (mean quality < 20)
% trimFiles is a cell array — pass directly to seqfilter
[trimFiles, nTrimmed] = seqtrim("reads_R1.fastq", ...
    Method="MeanQuality", Threshold=20, WindowSize=5, OverWrite=true);

% Filter reads shorter than 50 bp after trimming
% nKept = reads passing filter, nRemoved = reads excluded
[filtFiles, nKept, nRemoved] = seqfilter(trimFiles, ...
    Method="MinLength", Threshold=50, OverWrite=true);

% Visualize quality after processing
seqqcplot(filtFiles, "QualityBoxplot");
```

For paired-end data, pass both files and use `PairedFiles`:

```matlab
% Filter paired reads together (both must pass)
% nKept/nRemoved are per-file vectors (one entry per input file)
[filtFiles, nKept, nRemoved] = seqfilter(["R1_trimmed.fastq", "R2_trimmed.fastq"], ...
    Method="MeanQuality", Threshold=20, PairedFiles=true, OverWrite=true);
```

See `references/ngs-qc-functions.md` for all method options and parameter details.

### RNA-Seq: Count and Test

Use `featurecount` + `rnaseqde` instead of manual SAM parsing and t-tests. The negative binomial model is statistically appropriate for count data.

```matlab
% Count reads per gene (handles multi-mapping, strand specificity)
samFiles = ["ctrl1.bam", "ctrl2.bam", "ctrl3.bam", ...
            "treat1.bam", "treat2.bam", "treat3.bam"];
countTable = featurecount("annotation.gtf", samFiles);

% Differential expression with built-in FDR correction
% IDColumns carries gene IDs into the output table (otherwise they're dropped)
diffTable = rnaseqde(countTable, ["ctrl1", "ctrl2", "ctrl3"], ...
    ["treat1", "treat2", "treat3"], IDColumns="ID");
```

For more control over the statistical model, use `nbintest` directly:

```matlab
% Extract count matrices (skip ID/Reference columns)
ctrlCounts = countTable{:, ["ctrl1", "ctrl2", "ctrl3"]};
treatCounts = countTable{:, ["treat1", "treat2", "treat3"]};

% Negative binomial test with local regression variance link
testResult = nbintest(ctrlCounts, treatCounts, VarianceLink="LocalRegression");  % rnaseqde names it "local"

% Access p-values and apply Benjamini-Hochberg FDR
pvals = testResult.pValue;
padj = mafdr(pvals, BHFDR=true);
```

See `references/rnaseq-de-pipeline.md` for normalization details and visualization patterns.

### BLAST: Submit and Parse Results

The `getblast` result structure uses specific field names. Do not guess — use these exactly:

```matlab
% Submit and retrieve
seq = fastaread("query.fasta");
RID = blastncbi(seq.Sequence, "blastn", Expect=1e-10, Database="nt");
results = getblast(RID, WaitTime=5);   % WaitTime is in minutes

% Parse hits — exact field names
for i = 1:min(10, numel(results.Hits))
    hit = results.Hits(i);
    hsp = hit.Hsps(1);
    fprintf("%s | E=%.2e | Identity=%.1f%%\n", ...
        hit.Definition, hsp.Expect, ...
        hsp.Identities / hsp.AlignmentLength * 100);
end
```

See `references/blast-result-structure.md` for the complete field reference.

## Output Types

- **`seqtrim` and `seqfilter` return cell arrays** of character vectors for output file paths, even when given a single string input. Use them directly for chaining (`seqfilter(trimFiles, ...)` works), but convert with `string()` before `fprintf` or string operations: `fprintf("Output: %s\n", string(trimFiles))`.
- **`seqfilter` output variables:** `[outFiles, nSeqIn, nSeqOut]` — `nSeqIn` = reads **kept** (selected into output), `nSeqOut` = reads **excluded** (filtered out). The total entering the filter is `nSeqIn + nSeqOut`.
- **Do not use `fastqinfo` to verify output file read counts.** It may report "Invalid FASTQ format" warnings and incorrect counts on files where `seqtrim` produced empty (fully trimmed) reads. Use `numel(fastqread(file))` for reliable verification.

## Common Mistakes

| Mistake | Why It's Wrong | Correct Approach |
|---------|---------------|-----------------|
| Manual quality trimming loops | Misses edge cases, slow, reinvents the wheel | `seqtrim` with appropriate `Method` |
| Building quality matrices for QC plots | Error-prone with variable-length reads | `seqqcplot` accepts FASTQ files directly |
| `ttest2` on RNA-Seq counts | t-test assumes normal distribution; count data is negative binomial | `rnaseqde` or `nbintest` |
| Manual SAM parsing with `fopen`/`fgetl` | Misses multi-mapping, flags, CIGAR strings | `featurecount` for counting; `BioMap` for access |
| Guessing BLAST result field names (`.HSPs`, `.Name`) | The struct fields don't match the XML tag names | Use the field map in `references/blast-result-structure.md` |
| `blastncbi(seq, 'blastn', 'ExpectValue', 1e-10)` | Wrong parameter name | `Expect` (not `ExpectValue`) |
| `geneontology(...)` | Function doesn't exist by that name | `geneont` (the class constructor) |
| `chipseqpeaks(...)` | Function doesn't exist; there is no built-in ChIP-seq peak caller (`mspeaks` is a mass-spec peak picker) | Compute coverage with `BioMap` + `getCounts` and threshold enriched windows |

### Purpose-built functions agents tend to hand-roll

| Task | Use | Notes |
|------|-----|-------|
| Restriction digest | `[frags, cuts] = restrict(seq, "EcoRI")` | Linear sequences only. `cuts` always starts with 0 (the sequence start), even with no sites; real sites are `cuts(cuts > 0)` |
| Base / codon composition | `basecount(seq)`, `codoncount(seq)` | Return structs of counts |
| Demultiplex by barcode | `[outFiles, counts] = seqsplit(fastqFile, barcodeFile)` (two outputs only) | Barcode file is headerless `name<TAB>barcode` lines; a header row errors "barcode sequences must have the same length". No `OverWrite` option: re-running into the same `OutputDir` errors if outputs exist, and `OutputDir` must already exist (`mkdir` it first) |
| GTF/GFF annotation | `g = GTFAnnotation(file); G = getGenes(getSubset(g, Reference="chr4"))` | `getGenes` returns a table (`GeneID`, `Start`, `Stop`, `Strand`, `NumTranscripts`); raw `getData` returns a struct array whose field is `Gene`, not `GeneID`; collect it with `{d.Gene}` (bare `d.Gene` expands to one argument per entry). Also `GFFAnnotation`, `getTranscripts`, `getExons`; reference names come from the file (`getReferenceNames`) |
| BAM flag filtering | `bm = BioMap(bam, SelectReference="seq1"); idx = filterByFlag(bm, PairedInMap=true)` | Combine with `bm.MappingQuality` for MAPQ filters |

### Removed functions (not in current releases)

Older examples use these; they error with "Unrecognized function or variable".

| Removed | Use instead |
|---------|-------------|
| `showalignment` | `[score, al] = nwalign(a, b); disp(al)` (3-row char: seq 1, match line, seq 2) |
| `multialignviewer`, `seqtool`, `seqviewer` | `seqalignviewer(alignment)` |
| `phytreetool` | `phytreeviewer(tree)` |
| `seqshoworfs` | No ORF finder: translate each frame with `nt2aa(seq, Frame=f, AlternativeStartCodons=false)` and take the longest `M...*` run |
| `affyread`, `celintensityread`, `gcrma`, `rmasummary`, `affyprobeseqread`, `probelibraryinfo` | Affymetrix import is gone: start from an exported expression matrix (`readtable`) |
| `DataMatrix` | `table` |
| `blastlocal`, `blastformat`, `blastreadlocal` | `blastplus` (BLAST+ support package) or the BLAST pipeline blocks |

## Pipeline Blocks

When building a `bioinfo.pipeline.Pipeline` (R2023a+) with bioinformatics steps, read `references/pipeline-blocks.md` for the pre-made `bioinfo.pipeline.block.*` blocks and their options, and use one of those before wrapping a function in `UserFunction`.

## Conventions

- **File-level operations first.** Prefer `seqtrim("file.fastq")` over reading into memory and trimming manually. File-level operations handle streaming, memory, and output automatically.
- **Always pass `OverWrite=true`** to standalone `seqtrim` and `seqfilter` calls you re-run (`seqsplit` has no such option, and the pipeline blocks reject `OverWrite`). Default is `false`, which errors if output files already exist.
- **`rnaseqde` over `nbintest` for standard DE.** Use `rnaseqde` (R2021b+) for the common case; it already takes `VarianceLink` and `FDRMethod` (lowercase `"bh"` (default) or `"storey"`; `"BH"` errors). Drop to `nbintest` only for custom size factors, pooled variance, or the `NegativeBinomialTest` object (e.g. `plotVarianceLink`). Both need 2+ replicates per condition and error with one sample per side, so tell the user before falling back to another test.
- **`featurecount` accepts multiple BAM/SAM files.** Pass a string array to count all samples in one call — no loops needed. Its `ID` column, like the `GeneID` column from `getGenes`, is a cell array of character vectors: wrap it in `string(...)` before `fprintf`.
- **Gene Ontology is object-oriented.** Create with `geneont('Live', true)` or `geneont('File', ...)`, then call methods like `getancestors`, `getdescendents`, `getrelatives` on the object.
- **Always specify encoding for QC functions** when working with older data. Default is `'Illumina18'` (Phred+33). Use `'Sanger'` for Sanger data, `'Illumina13'`/`'Illumina15'` for older Illumina. Pass it as `Encoding=` to `seqtrim`/`seqfilter`, but as the positional 3rd argument to `seqqcplot` (`seqqcplot(f, "QualityBoxplot", "Sanger")`; `Encoding=` errors there).
- **Use `tiledlayout`/`nexttile`** for multi-panel figures, not `subplot`. `seqqcplot` always opens its own figure, so don't set up a figure or tile for it.

----

Copyright 2026 The MathWorks, Inc.

----

Files in this skill

  • SKILL.md17.6 KB
  • manifest.yaml718 B
  • references/blast-result-structure.md4.7 KB
  • references/ngs-qc-functions.md6.1 KB
  • references/pipeline-blocks.md3.3 KB
  • references/rnaseq-de-pipeline.md6.1 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.