Skip to content

Examples

github-actions[bot] edited this page Mar 22, 2026 · 20 revisions

Examples

This page provides practical, ready-to-run MATLAB examples demonstrating key features of the MATLAB MCP Server. Progress from simple calculations to advanced signal processing and async jobs.

Architecture Overview

graph LR
    Agent["AI Agent<br/>(Claude, Cursor, etc.)"]
    Agent -->|"execute_code<br/>check_code<br/>read_image"| Server["MCP Server"]
    Server -->|Pool Acquire| Pool["Engine Pool<br/>2-8 engines"]
    Server -->|Job Exec| Executor["Job Executor<br/>Sync/Async"]
    Executor -->|Create Job| Tracker["Job Tracker"]
    Executor -->|Extract Props| MATLAB["MATLAB Engine<br/>2020b+"]
    MATLAB -->|Figures| Converter["Plotly Converter"]
    Converter -->|JSON + PNG| Agent
Loading

Basic Calculations

Simple Matrix Operations

Demonstrates: Basic MATLAB arithmetic, matrix operations, output formatting

Prerequisites: None

% Create matrices and perform operations
A = [1 2 3; 4 5 6; 7 8 9];
B = [9 8 7; 6 5 4; 3 2 1];

% Element-wise operations
C = A + B;
D = A .* B;

% Matrix operations
E = A * B';
trace_val = trace(E);

% Display results
fprintf('Sum of A and B:\n');
disp(C);
fprintf('\nMatrix product trace: %.2f\n', trace_val);

Eigenvalue Decomposition

Demonstrates: Linear algebra functions, symbolic computation

% Create a symmetric matrix
A = [4 -1 0; -1 3 -2; 0 -2 5];

% Compute eigenvalues and eigenvectors
[V, D] = eig(A);

fprintf('Eigenvalues:\n');
disp(diag(D));

fprintf('\nEigenvectors:\n');
disp(V);

% Verify: A*V should equal V*D
residual = norm(A*V - V*D);
fprintf('Residual error: %.2e\n', residual);

Solving Linear Systems

Demonstrates: Linear system solving, condition number analysis

% System: 3x + 2y - z = 1
%         2x - 2y + 4z = -2
%        -x + 0.5y - z = 0

A = [3 2 -1; 2 -2 4; -1 0.5 -1];
b = [1; -2; 0];

x = A \ b;

fprintf('Solution:\n');
fprintf('x = %.4f\n', x(1));
fprintf('y = %.4f\n', x(2));
fprintf('z = %.4f\n', x(3));

% Verify solution
residual = norm(A*x - b);
fprintf('\nResidual norm: %.2e\n', residual);

% Condition number
cond_num = cond(A);
fprintf('Condition number: %.2f\n', cond_num);

Plotting & Visualization

All plots are automatically converted to interactive Plotly JSON with static PNG thumbnails.

Line Plot with Styling

Demonstrates: Basic plotting, line styles, axis labels, grid

% Create smooth curve
x = linspace(0, 2*pi, 500);
y = sin(x);

plot(x, y, 'LineWidth', 2.5, 'Color', [0.2 0.4 0.8]);
hold on;
plot(x, cos(x), 'LineWidth', 2, 'Color', [0.9 0.3 0.2]);

xlabel('x (radians)', 'FontSize', 12);
ylabel('Amplitude', 'FontSize', 12);
title('Trigonometric Functions', 'FontSize', 14, 'FontWeight', 'bold');
legend('sin(x)', 'cos(x)', 'FontSize', 11);
grid on;
xlim([0 2*pi]);
ylim([-1.2 1.2]);

Scatter Plot with Markers

Demonstrates: Scatter plots, marker customization, color mapping

% Generate random data
n = 200;
x = randn(n, 1);
y = randn(n, 1);
c = sqrt(x.^2 + y.^2);  % Distance from origin

scatter(x, y, 50, c, 'filled', 'MarkerEdgeColor', 'k', 'LineWidth', 0.5);
colorbar;
colormap('viridis');
xlabel('X');
ylabel('Y');
title('Scatter Plot with Distance Coloring');

3D Surface Plot

Demonstrates: 3D visualization, surface shading, colormap

% Create mesh grid
[X, Y] = meshgrid(-5:0.2:5, -5:0.2:5);
Z = peaks(X, Y);

figure;
surf(X, Y, Z, 'EdgeColor', 'none');
shading interp;
colormap('jet');
colorbar;

xlabel('X');
ylabel('Y');
zlabel('Z');
title('Peaks Function (3D Surface)');
view(45, 30);

Multiple Subplots

Demonstrates: Subplot layout, multi-panel figures

% Generate time series
t = linspace(0, 1, 1000);
frequencies = [5 10 20 50];

for i = 1:4
    subplot(2, 2, i);
    plot(t, sin(2*pi*frequencies(i)*t), 'LineWidth', 1.5);
    title(sprintf('%d Hz Sine Wave', frequencies(i)));
    xlabel('Time (s)');
    ylabel('Amplitude');
    grid on;
end

Heatmap

Demonstrates: Heatmaps, matrix visualization, annotated colormaps

% Create correlation matrix
data = randn(50, 100);
corr_matrix = corr(data);

imagesc(corr_matrix);
colormap('RdBu');
colorbar;
caxis([-1 1]);
title('Correlation Matrix Heatmap');
xlabel('Variable Index');
ylabel('Variable Index');

Signal Processing

FFT Analysis

Demonstrates: Fourier transform, frequency domain analysis, multi-trace plots

Prerequisites: Signal Processing Toolbox (optional, but recommended)

% Generate multi-frequency signal
fs = 8000;  % Sampling frequency
t = 0:1/fs:0.5;  % 0.5 second signal

% Sum of three sine waves: 440Hz, 880Hz, 1320Hz
signal = sin(2*pi*440*t) + 0.5*sin(2*pi*880*t) + 0.3*sin(2*pi*1320*t);
noise = 0.1 * randn(size(t));
signal = signal + noise;

% Compute FFT
N = length(signal);
Y = fft(signal);
f = (0:N-1) * fs / N;

% Plot time domain and frequency domain
subplot(2, 1, 1);
plot(t(1:2000), signal(1:2000));
xlabel('Time (s)');
ylabel('Amplitude');
title('Time Domain Signal');
grid on;

subplot(2, 1, 2);
plot(f(1:N/2), abs(Y(1:N/2))/N);
xlabel('Frequency (Hz)');
ylabel('Magnitude');
title('Frequency Domain (FFT)');
xlim([0 2000]);
grid on;

Digital Filter Design

Demonstrates: Filter design, frequency response, cascaded filtering

% Design Butterworth lowpass filter
fc = 1000;  % Cutoff frequency (Hz)
fs = 8000;  % Sampling frequency
Wn = fc / (fs/2);  % Normalized frequency
[b, a] = butter(4, Wn);

% Generate input signal (mix of frequencies)
t = 0:1/fs:0.1;
signal = sin(2*pi*500*t) + sin(2*pi*2000*t);  % 500Hz + 2000Hz

% Apply filter
filtered = filter(b, a, signal);

% Plot
subplot(2, 1, 1);
plot(t, signal);
title('Original Signal (500Hz + 2000Hz)');
xlabel('Time (s)');

subplot(2, 1, 2);
plot(t, filtered);
title('Filtered Signal (Lowpass @ 1kHz)');
xlabel('Time (s)');

Spectrogram

Demonstrates: Time-frequency analysis, 2D visualization

% Create chirp signal
t = 0:0.01:5;
f0 = 10;  % Initial frequency
f1 = 100;  % Final frequency
chirp_signal = chirp(t, f0, t(end), f1);

% Compute spectrogram
window = hamming(256);
noverlap = 200;
nfft = 512;

[S, F, T, P] = spectrogram(chirp_signal, window, noverlap, nfft, 100);

% Plot
imagesc(T, F, 10*log10(abs(P)));
axis xy;
colormap('jet');
colorbar;
xlabel('Time (s)');
ylabel('Frequency (Hz)');
title('Spectrogram of Chirp Signal (10–100 Hz)');
ylim([0 50]);

Statistics & Data Analysis

Hypothesis Testing

Demonstrates: Statistical functions, summary statistics, formatted output

% Generate two samples
sample1 = randn(100, 1) + 2;  % Mean = 2
sample2 = randn(100, 1);      % Mean = 0

% Perform t-test
[h, p, ~, stats] = ttest2(sample1, sample2);

fprintf('=== Two-Sample t-Test ===\n');
fprintf('Sample 1 mean: %.4f (std: %.4f)\n', mean(sample1), std(sample1));
fprintf('Sample 2 mean: %.4f (std: %.4f)\n', mean(sample2), std(sample2));
fprintf('Test statistic: %.4f\n', stats.tstat);
fprintf('p-value: %.6f\n', p);
fprintf('Reject null hypothesis: %s\n', string(logical(h)));

Descriptive Statistics

Demonstrates: Statistical summaries, percentiles, data distribution

% Generate sample data
data = randn(1000, 1);

% Calculate statistics
mean_val = mean(data);
median_val = median(data);
std_val = std(data);
q25 = prctile(data, 25);
q75 = prctile(data, 75);

fprintf('=== Descriptive Statistics ===\n');
fprintf('Mean: %.4f\n', mean_val);
fprintf('Median: %.4f\n', median_val);
fprintf('Std Dev: %.4f\n', std_val);
fprintf('IQR (Q25-Q75): %.4f\n', q75 - q25);
fprintf('Skewness: %.4f\n', skewness(data));
fprintf('Kurtosis: %.4f\n', kurtosis(data));

% Plot histogram
histogram(data, 30, 'Normalization', 'probability');
hold on;
x = linspace(min(data), max(data), 100);
pdf = normpdf(x, mean_val, std_val);
plot(x, pdf, 'LineWidth', 2, 'Color', 'r');
xlabel('Value');
ylabel('Probability');
title('Data Distribution vs. Normal PDF');
legend('Histogram', 'Normal PDF');

Async Jobs (Long-Running Tasks)

Jobs exceeding sync_timeout (default 30s) are automatically promoted to async execution. Use mcp_progress() to report progress.

Monte Carlo π Estimation

Demonstrates: Async execution, progress reporting, numerical methods

% Monte Carlo estimation of pi
n_trials = 1e6;
inside = 0;

for i = 1:n_trials
    x = rand();
    y = rand();
    if x^2 + y^2 <= 1
        inside = inside + 1;
    end
    
    % Report progress every 100k trials
    if mod(i, 100000) == 0
        progress = (i / n_trials) * 100;
        mcp_progress(__mcp_job_id__, progress, ...
            sprintf('Trial %d/%d', i, n_trials));
    end
end

pi_estimate = 4 * inside / n_trials;
fprintf('Estimated π: %.6f (error: %.6f)\n', pi_estimate, abs(pi_estimate - pi));

Agent interaction:

  1. Submits code → receives job_id immediately
  2. Polls get_job_status(job_id) → sees "Trial 100000/1000000 — 10%"
  3. Continues polling → sees progress updates
  4. Once complete → calls get_job_result(job_id) → receives final value

Matrix SVD Decomposition

Demonstrates: Large-scale numerical computation, async promotion

% Create a large matrix
n = 5000;
A = randn(n, n);

% Progress indicator
fprintf('Computing SVD of %dx%d matrix...\n', n, n);
mcp_progress(__mcp_job_id__, 0, 'Starting SVD decomposition');

% Compute thin SVD
[U, S, V] = svd(A, 'econ');

mcp_progress(__mcp_job_id__, 50, 'SVD computed, analyzing...');

% Compute rank via singular values
tol = max(size(A)) * eps(max(S(:)));
rank_A = sum(diag(S) > tol);

% Compute condition number
cond_num = S(1) / S(end);

fprintf('Matrix rank: %d\n', rank_A);
fprintf('Condition number: %.4e\n', cond_num);
fprintf('Largest singular value: %.4f\n', S(1));
fprintf('Smallest singular value: %.4e\n', S(end));

mcp_progress(__mcp_job_id__, 100, 'Complete');

Iterative Solver with Convergence Tracking

Demonstrates: Iterative algorithms, progress milestones, convergence criteria

% Solve: x = tanh(x)
% Using fixed-point iteration: x_{n+1} = tanh(x_n)

x = 1.0;
max_iter = 10000;
tol = 1e-10;
history = [x];

for iter = 1:max_iter
    x_new = tanh(x);
    
    if mod(iter, 1000) == 0
        error = abs(x_new - x);
        progress = (iter / max_iter) * 100;
        mcp_progress(__mcp_job_id__, progress, ...
            sprintf('Iteration %d, error=%.2e', iter, error));
    end
    
    if abs(x_new - x) < tol
        fprintf('Converged in %d iterations\n', iter);
        break
    end
    
    x = x_new;
    history = [history; x];
end

fprintf('Solution: x = %.10f\n', x);
fprintf('Verification: tanh(x) = %.10f\n', tanh(x));

File Operations & Data Exchange

Upload Data & Process

% Assume agent uploaded a CSV file: "input.csv"
% Read the CSV
data = readtable('input.csv');

% Process
results = table();
results.ID = data.ID;
results.Original = data.Value;
results.Squared = data.Value.^2;
results.LogTransform = log(data.Value + 1);

% Save results
writetable(results, 'results.csv');
fprintf('Processed %d rows, saved to results.csv\n', height(results));

Agent workflow:

  1. Calls upload_data(filename="input.csv", content_base64="...")
  2. Executes the MATLAB code above
  3. Calls read_data(filename="results.csv") to retrieve results

Save & Load MAT Files

% Generate data
x = linspace(0, 10*pi, 1000);
y = sin(x);
z = cos(x);
metadata = struct('description', 'Trig functions', 'samples', 1000);

% Save
save('mydata.mat', 'x', 'y', 'z', 'metadata');
fprintf('Saved mydata.mat\n');

% Later: load
load('mydata.mat');
fprintf('Loaded: %d samples\n', metadata.samples);
disp(metadata.description);

Configuration Templates

Minimal (Single-User Local)

server:
  transport: stdio
  log_level: info

pool:
  min_engines: 1
  max_engines: 2
  startup_timeout_seconds: 60

execution:
  sync_timeout: 30
  max_output_chars: 50000

security:
  blocked_functions_enabled: true

Use case: Local development, single AI agent session

Multi-User Production

server:
  transport: sse
  host: 0.0.0.0
  port: 8765
  log_level: warning
  log_file: /var/log/matlab-mcp/server.log

pool:
  min_engines: 4
  max_engines: 16
  proactive_warmup_threshold: 0.75
  idle_scale_down_timeout: 900

execution:
  sync_timeout: 60
  max_output_chars: 100000
  temp_dir: /var/tmp/matlab-mcp

workspace:
  clear_between_sessions: true

security:
  blocked_functions_enabled: true
  max_upload_size_mb: 500
  require_proxy_auth: true

sessions:
  max_sessions: 100
  session_timeout: 7200
  job_retention_seconds: 86400

monitoring:
  enabled: true
  db_path: /var/lib/matlab-mcp/metrics.db

Use case: Enterprise deployment, multiple concurrent users, Plotly plots, monitoring dashboard

Using Custom Tools

Define custom MATLAB functions in custom_tools.yaml:

tools:
  - name: "analyze_signal"
    function: "signal_analysis"
    description: "Analyze frequency content of a signal"
    parameters:
      signal_file:
        type: string
        description: "Path to .csv file with signal samples"
        required: true
      sample_rate:
        type: float
        description: "Sampling rate in Hz"
        required: true

  - name: "train_model"
    function: "ml.training.train_classifier"
    description: "Train a classifier on training data"
    parameters:
      data_file:
        type: string
        required: true
      model_type:
        type: string
        enum: ["svm", "tree", "ensemble"]
        default: "svm"

Agent usage:

  • "Analyze the frequency content of signal.csv (sampled at 44100 Hz)" → calls analyze_signal
  • "Train a classifier using ensemble method" → calls train_model

Running Examples Through Your Agent

Claude Desktop / Cursor:

"Execute this MATLAB code to plot a sine wave and show me the result."

Programmatic (Python):

import httpx
from base64 import b64encode

# Upload data
file_content = b"x,y,z\n1,2,3\n4,5,6"
response = httpx.post("http://localhost:8765/upload_data", json={
    "filename": "data.csv",
    "content_base64": b64encode(file_content).decode()
})

# Execute code
response = httpx.post("http://localhost:8765/execute_code", json={
    "code": "load('data.csv'); disp('Data loaded');"
})

See the examples/ directory in the repository for additional template configurations and MATLAB scripts.

Clone this wiki locally