Skip to content

Examples

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

Examples

Ready-to-run examples are in the examples/ directory. You don't run these directly — ask your AI agent to execute them!

Basic Usage

Simple Calculation

"Calculate the eigenvalues of a 3x3 magic square"

A = magic(3);
eigenvalues = eig(A);
disp('Eigenvalues of a 3x3 magic square:');
disp(eigenvalues);

Matrix Operations

"Create two 100x100 random matrices, multiply them, and show the trace"

n = 100;
A = rand(n);
B = rand(n);
C = A * B;
fprintf('Result matrix size: %dx%d\n', size(C, 1), size(C, 2));
fprintf('Max element: %.4f\n', max(C(:)));
fprintf('Trace: %.4f\n', trace(C));

Solve a Linear System

"Solve this system of equations: 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;
disp('Solution to Ax = b:');
disp(x);

Statistics and Data Analysis

"Analyze a dataset: compute mean, standard deviation, median, and range"

data = randn(1, 10000);
fprintf('Mean:   %.4f\n', mean(data));
fprintf('Std:    %.4f\n', std(data));
fprintf('Median: %.4f\n', median(data));
fprintf('Min:    %.4f\n', min(data));
fprintf('Max:    %.4f\n', max(data));

Working with Tables

"Create a table of people with names, ages, and scores"

names = {'Alice'; 'Bob'; 'Charlie'; 'Diana'};
ages = [30; 25; 35; 28];
scores = [95.5; 88.0; 92.3; 97.1];
T = table(names, ages, scores, 'VariableNames', {'Name', 'Age', 'Score'});
disp(T);
fprintf('Average score: %.1f\n', mean(T.Score));

Plotting

All figures are automatically converted to interactive Plotly JSON + static PNG.

Line Plot

"Plot sin(x) from 0 to 2π"

x = linspace(0, 2*pi, 100);
y = sin(x);
figure;
plot(x, y, 'b-', 'LineWidth', 2);
xlabel('x');
ylabel('sin(x)');
title('Sine Wave');
grid on;

Multiple Lines

"Plot sin, cos, and their product on the same graph"

x = linspace(0, 2*pi, 200);
figure;
plot(x, sin(x), 'r-', 'LineWidth', 2); hold on;
plot(x, cos(x), 'b--', 'LineWidth', 2);
plot(x, sin(x) .* cos(x), 'g-.', 'LineWidth', 2);
legend('sin(x)', 'cos(x)', 'sin(x)*cos(x)');
xlabel('x'); ylabel('y');
title('Trigonometric Functions');
grid on;

Scatter Plot

"Create a scatter plot showing correlation between two variables"

n = 500;
x = randn(n, 1);
y = 2*x + randn(n, 1) * 0.5;
figure;
scatter(x, y, 20, 'filled', 'MarkerFaceAlpha', 0.5);
xlabel('X'); ylabel('Y');
title(sprintf('Scatter Plot (n=%d, r=%.2f)', n, corr(x, y)));
grid on;

Bar Chart

"Show quarterly revenue as a bar chart"

categories = {'Q1', 'Q2', 'Q3', 'Q4'};
revenue = [150 230 180 310];
figure;
bar(revenue);
set(gca, 'XTickLabel', categories);
ylabel('Revenue ($K)');
title('Quarterly Revenue');
grid on;

Histogram

"Plot a histogram of normally distributed data"

data = randn(10000, 1);
figure;
histogram(data, 50, 'FaceColor', [0.2 0.6 0.8], 'EdgeColor', 'white');
xlabel('Value');
ylabel('Count');
title('Normal Distribution (10,000 samples)');

3D Surface

"Show me the peaks function as a 3D surface"

[X, Y] = meshgrid(-3:0.1:3, -3:0.1:3);
Z = peaks(X, Y);
figure;
surf(X, Y, Z);
xlabel('X'); ylabel('Y'); zlabel('Z');
title('Peaks Function');
colorbar;
shading interp;

Multiple Subplots

"Plot 4 different frequency sine waves in subplots"

t = linspace(0, 1, 1000);
figure;
subplot(2,2,1);
plot(t, sin(2*pi*5*t)); title('5 Hz');
subplot(2,2,2);
plot(t, sin(2*pi*10*t)); title('10 Hz');
subplot(2,2,3);
plot(t, sin(2*pi*20*t)); title('20 Hz');
subplot(2,2,4);
plot(t, sin(2*pi*5*t) + sin(2*pi*20*t)); title('5 + 20 Hz');
sgtitle('Signal Frequencies');

Heatmap

"Create a heatmap visualization of random data"

data = rand(20, 20);
figure;
imagesc(data);
colorbar;
title('Random Heatmap');
xlabel('Column'); ylabel('Row');

Signal Processing

FFT Analysis

"Generate a 440Hz signal with noise, compute its FFT, and show both time and frequency domains"

fs = 8000;                    % Sample rate
t = 0:1/fs:0.1;              % 100ms duration
f1 = 440;                    % A4 note
f2 = 880;                    % A5 note

signal = sin(2*pi*f1*t) + 0.5*sin(2*pi*f2*t);
noisy = signal + 0.3*randn(size(t));

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

figure;
subplot(2,1,1);
plot(t*1000, noisy);
xlabel('Time (ms)'); ylabel('Amplitude');
title('Noisy Signal (440 Hz + 880 Hz)');

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

Low-Pass Butterworth Filter

"Filter a noisy 500Hz signal with a Butterworth filter" (requires Signal Processing Toolbox)

fs = 8000;
t = 0:1/fs:0.1;
clean = sin(2*pi*500*t);
noisy = clean + 0.8*randn(size(t));

[b, a] = butter(6, 1000/(fs/2));  % 6th order, 1kHz cutoff
filtered = filter(b, a, noisy);

figure;
subplot(3,1,1);
plot(t*1000, clean); title('Clean Signal');
subplot(3,1,2);
plot(t*1000, noisy); title('Noisy Signal');
subplot(3,1,3);
plot(t*1000, filtered); title('Filtered Signal');
xlabel('Time (ms)');

Spectrogram

"Show a spectrogram of a chirp signal (frequency sweep from 100 Hz to 2000 Hz)" (requires Signal Processing Toolbox)

fs = 8000;
t = 0:1/fs:1;
% Chirp signal: frequency increases from 100 Hz to 2000 Hz
f0 = 100; f1 = 2000;
signal = chirp(t, f0, 1, f1);

figure;
spectrogram(signal, 256, 200, 512, fs, 'yaxis');
title('Chirp Signal Spectrogram (100-2000 Hz)');
colorbar;

Long-Running Jobs (Async)

Jobs that exceed sync_timeout are automatically promoted to async. Use mcp_progress() to report progress.

Monte Carlo Pi Estimation

"Run a Monte Carlo simulation to estimate π using 1 million random trials"

n = 1e6;
inside = 0;
for i = 1:n
    x = rand();
    y = rand();
    if x^2 + y^2 <= 1
        inside = inside + 1;
    end
    % Report progress every 10%
    if mod(i, n/10) == 0
        mcp_progress(__mcp_job_id__, i/n*100, ...
            sprintf('Processed %d/%d trials', i, n));
    end
end
pi_estimate = 4 * inside / n;
fprintf('Pi estimate: %.6f (error: %.6f)\n', pi_estimate, abs(pi - pi_estimate));

The agent gets a job ID immediately and can poll progress:

  • "Processed 100000/1000000 trials — 10%"
  • "Processed 500000/1000000 trials — 50%"
  • ...until complete.

Large Matrix Computation

"Create a 5000x5000 random matrix and compute its SVD and condition number"

n = 5000;
fprintf('Creating %dx%d random matrix...\n', n, n);
A = rand(n);
fprintf('Computing SVD...\n');
[U, S, V] = svd(A);
fprintf('Top 5 singular values: ');
disp(diag(S(1:5, 1:5))');
fprintf('Condition number: %.2e\n', cond(A));

Iterative Solver with Progress

"Solve a linear system using iterative Jacobi method with progress reporting"

n = 1000;
A = rand(n) + n*eye(n);  % diagonally dominant
b = rand(n, 1);
x = zeros(n, 1);
max_iter = 500;
tol = 1e-10;

for iter = 1:max_iter
    x_new = (b - (A - diag(diag(A))) * x) ./ diag(A);
    err = norm(x_new - x) / norm(x_new);
    x = x_new;

    if mod(iter, 50) == 0
        mcp_progress(__mcp_job_id__, iter/max_iter*100, ...
            sprintf('Iteration %d/%d, error=%.2e', iter, max_iter, err));
    end

    if err < tol
        fprintf('Converged at iteration %d (error=%.2e)\n', iter, err);
        break;
    end
end
fprintf('Residual norm: %.2e\n', norm(A*x - b));

File Reading

The server provides tools to read files back from the session temp directory — useful for retrieving generated scripts, data, and plots.

Read a MATLAB Script

"Show me the contents of the script you just saved"

The agent calls read_script:

read_script(filename="analysis.m")

Returns the .m file content as inline text.

Read Data File Summary

"What variables are in the results.mat file?"

The agent calls read_data in summary mode:

read_data(filename="results.mat", format="summary")

Returns a table of variable names, sizes, and types (via MATLAB whos). Use format="raw" to get the raw base64-encoded file content instead.

Read CSV Data

"Show me the output CSV"

read_data(filename="output.csv", format="summary")

Returns the text content of the CSV file inline.

View a Generated Plot

"Show me the plot you just created"

The agent calls read_image:

read_image(filename="result.png")

Returns the image as an inline content block — renders directly in Claude Desktop, Cursor, and other agent UIs. Supported formats: .png, .jpg, .gif.

Configuration Examples

Minimal (Single User)

server:
  transport: "stdio"
  log_level: "info"

pool:
  min_engines: 1
  max_engines: 2

Multi-User Server

server:
  transport: "sse"
  host: "0.0.0.0"
  port: 8765

pool:
  min_engines: 4
  max_engines: 16

security:
  require_proxy_auth: true

sessions:
  max_sessions: 100

See the full examples/ directory for more.

Clone this wiki locally