
matlab-skills
A collection of agent skills for MATLAB development
- version
- 1.0.1
- GitHub stars
- 55
Install
/plugin install matlab-skills@matlab-skillsRun it inside Claude Code after adding the marketplace with /plugin marketplace add matlab/skills.
Contents
Discovered from sourceSkills 4
MATLAB Performance Optimizer
Optimize MATLAB code performance with vectorization, memory management, and profiling tools.
When to Use This Skill
- Optimizing slow or inefficient MATLAB code
- Converting loops to vectorized operations
- Reducing memory usage
- Improving algorithm performance
- When user mentions: slow, performance, optimize, speed up, efficient, memory
- Profiling code to find bottlenecks
- Parallelizing computations
Core Optimization Principles
1. Vectorization (Most Important)
Replace loops with vectorized operations whenever possible.
SLOW - Using loops:
% Slow approach
n = 1000000;
result = zeros(n, 1);
for i = 1:n
result(i) = sin(i) * cos(i);
end
FAST - Vectorized:
% Fast approach
n = 1000000;
i = (1:n).';
result = sin(i) .* cos(i);
2. Preallocate Arrays
Always preallocate arrays before loops.
SLOW - Growing arrays:
% Very slow - array grows each iteration
result = [];
for i = 1:10000
result(end+1) = i^2;
end
FAST - Preallocated:
% Fast - preallocated array
n = 10000;
result = zeros(n, 1);
for i = 1:n
result(i) = i^2;
end
3. Use Built-in Functions
MATLAB built-in functions are highly optimized.
SLOW - Manual implementation:
% Slow
sum_val = 0;
for i = 1:length(x)
sum_val = sum_val + x(i);
end
FAST - Built-in function:
% Fast
sum_val = sum(x);
Vectorization Techniques
Element-wise Operations
Use .*, ./, .^ for element-wise operations:
% Instead of this:
for i = 1:length(x)
y(i) = x(i)^2 + 2*x(i) + 1;
end
% Do this:
y = x.^2 + 2*x + 1;
Logical Indexing
Replace conditional loops with logical indexing:
% Instead of this:
count = 0;
for i = 1:length(data)
if data(i) > threshold
count = count + 1;
filtered(count) = data(i);
end
end
filtered = filtered(1:count);
% Do this:
filtered = data(data > threshold);
Matrix Operations
Use matrix multiplication instead of nested loops:
% Instead of this:
C = zeros(size(A, 1), size(B, 2));
for i = 1:size(A, 1)
for j = 1:size(B, 2)
for k = 1:size(A, 2)
C(i,j) = C(i,j) + A(i,k) * B(k,j);
end
end
end
% Do this:
C = A * B;
Cumulative Operations
Use cumsum, cumprod, cummax, cummin:
% Instead of this:
running_sum = zeros(size(data));
running_sum(1) = data(1);
for i = 2:length(data)
running_sum(i) = running_sum(i-1) + data(i);
end
% Do this:
running_sum = cumsum(data);
Memory Optimization
Use Appropriate Data Types
% Instead of default double (8 bytes)
data = rand(1000, 1000); % 8 MB
% Use single precision when appropriate (4 bytes)
data = single(rand(1000, 1000)); % 4 MB
% Use integers when applicable
indices = uint32(1:1000000); % 4 MB instead of 8 MB
Sparse Matrices
For matrices with mostly zeros:
% Dense matrix (wastes memory)
A = zeros(10000, 10000);
A(1:100, 1:100) = rand(100); % 800 MB
% Sparse matrix (efficient)
A = sparse(10000, 10000);
A(1:100, 1:100) = rand(100); % Only stores non-zeros
Clear Unused Variables
% Process large data
largeData = loadData();
processedData = processData(largeData);
% Clear when no longer needed
clear largeData;
% Continue with processed data
results = analyze(processedData);
In-Place Operations
% Instead of creating copies
A = A + 5; % In-place when possible
% Avoid unnecessary copies
B = A; % Creates copy if A is modified later
B = A + 0; % Forces copy
Profiling and Benchmarking
Using the Profiler
% Profile code execution
profile on
myFunction(inputs);
profile viewer
profile off
The profiler shows:
- Time spent in each function
- Number of calls to each function
- Lines that take the most time
Timing Comparisons
% Time single execution
tic;
result = myFunction(data);
elapsedTime = toc;
% Benchmark with timeit (more accurate)
timeit(@() myFunction(data))
% Compare multiple approaches
time1 = timeit(@() approach1(data));
time2 = timeit(@() approach2(data));
fprintf('Approach 1: %.6f s\nApproach 2: %.6f s\n', time1, time2);
Common Optimization Patterns
Pattern 1: Replace find with Logical Indexing
% SLOW
indices = find(x > 5);
y = x(indices);
% FAST
y = x(x > 5);
Pattern 2: Use Implicit Expansion Instead of repmat
% SLOW - repmat to match dimensions
A = rand(1000, 5);
B = rand(1, 5);
C = A - repmat(B, size(A, 1), 1);
% FAST - implicit expansion (R2016b+)
C = A - B;
Pattern 3: Avoid Repeated Calculations
% SLOW - recalculates each iteration
for i = 1:n
result(i) = data(i) / sqrt(sum(data.^2));
end
% FAST - calculate once
norm_factor = sqrt(sum(data.^2));
for i = 1:n
result(i) = data(i) / norm_factor;
end
% EVEN FASTER - vectorize
result = data / sqrt(sum(data.^2));
Pattern 4: Efficient String Operations
% SLOW - concatenating in loop
str = '';
for i = 1:1000
str = [str, sprintf('Line %d\n', i)];
end
% FAST - cell array + join
lines = cell(1000, 1);
for i = 1:1000
lines{i} = sprintf('Line %d', i);
end
str = strjoin(lines, '\n');
% FASTEST - vectorized sprintf
str = sprintf('Line %d\n', 1:1000);
Pattern 5: Use Table for Mixed Data Types
% Instead of separate arrays
names = cell(1000, 1);
ages = zeros(1000, 1);
scores = zeros(1000, 1);
% Use table
data = table(names, ages, scores);
% Faster access and better organization
Algorithm-Specific Optimizations
Convolution and Filtering
% Use built-in functions
filtered = conv(signal, kernel, 'same');
filtered = filter(b, a, signal);
% For 2D
filtered = conv2(image, kernel, 'same');
filtered = imfilter(image, kernel);
% FFT-based for large kernels (zero-pad for linear convolution)
nfft = length(signal) + length(kernel) - 1;
filtered = ifft(fft(signal, nfft) .* fft(kernel, nfft));
Distance Calculations
% Instead of nested loops for pairwise distances
% SLOW
n = size(points, 1);
distances = zeros(n, n);
for i = 1:n
for j = 1:n
distances(i,j) = norm(points(i,:) - points(j,:));
end
end
% FAST - vectorized
distances = pdist2(points, points);
Sorting and Searching
% Presort for multiple searches
sortedData = sort(data);
% Binary search on sorted data
idx = find(sortedData >= value, 1, 'first');
% Use ismember for set operations
[isPresent, locations] = ismember(searchValues, data);
% Use unique for removing duplicates
uniqueData = unique(data);
Parallel Computing
Simple Parallel Loops (parfor)
% Convert for to parfor for independent iterations
parfor i = 1:n
results(i) = expensiveFunction(data(i));
end
Requirements for parfor:
- Iterations must be independent
- Loop variable must be consecutive integers
- Variables must be classified as loop, sliced, broadcast, or reduction
Parallel Array Operations
% Create parallel pool
parpool('local', 4); % 4 workers
% Use parfeval for asynchronous parallel execution
futures = parfeval(@expensiveFunction, 1, data);
result = fetchOutputs(futures);
% GPU arrays for massive parallelization
gpuData = gpuArray(data);
result = arrayfun(@myFunction, gpuData);
result = gather(result); % Bring back to CPU
Advanced Optimizations
MEX Functions for Critical Sections
Convert performance-critical code to C/C++:
% Create MEX file for bottleneck function
% Write myFunction.c, then compile:
% mex myFunction.c
% Call like regular MATLAB function
result = myFunction(inputs);
Persistent Variables for Cached Results
function result = expensiveComputation(input)
persistent cachedData cachedInput
if isequal(input, cachedInput)
% Return cached result
result = cachedData;
return;
end
% Compute and cache
result = computeExpensiveOperation(input);
cachedData = result;
cachedInput = input;
end
JIT Acceleration Best Practices
MATLAB's JIT (Just-In-Time) compiler optimizes:
- Simple for-loops with scalar operations
- Functions without dynamic features
JIT-friendly code:
function result = jitFriendly(n)
result = 0;
for i = 1:n
result = result + i;
end
end
JIT-unfriendly code (avoid):
function result = jitUnfriendly(n)
result = 0;
for i = 1:n
eval(['x' num2str(i) ' = i;']); % Dynamic code
end
end
Performance Checklist
Before finalizing optimized code, verify:
- Loops are vectorized where possible
- Arrays are preallocated before loops
- Built-in functions used instead of manual implementations
- Logical indexing used instead of find + indexing
- Appropriate data types used (single vs double, integers)
- Sparse matrices used for sparse data
- Repeated calculations moved outside loops
- String concatenation uses efficient methods
- Code profiled to identify actual bottlenecks
- Matrix operations used instead of element-wise loops
- Parallel computing considered for independent operations
- Memory-intensive operations optimized
- Caching implemented for repeated expensive calls
Profiling Workflow
-
Measure First: Profile before optimizing
profile on myScript; profile viewer -
Identify Bottlenecks: Focus on functions taking most time
-
Optimize: Apply appropriate techniques
-
Measure Again: Verify improvement
% Before time_before = timeit(@() myFunction(data)); % After optimization time_after = timeit(@() myFunctionOptimized(data)); fprintf('Speedup: %.2fx\n', time_before/time_after); -
Iterate: Repeat for remaining bottlenecks
Common Performance Pitfalls
Pitfall 1: Premature Optimization
- Profile first, optimize second
- Focus on actual bottlenecks, not assumptions
Pitfall 2: Over-vectorization
- Sometimes loops are clearer and fast enough
- Balance readability with performance
Pitfall 3: Ignoring Memory Access Patterns
% SLOW - inner loop over columns (row-major traversal in column-major MATLAB)
for i = 1:rows
for j = 1:cols
A(i,j) = process(i, j);
end
end
% FAST - inner loop over rows (column-major traversal, contiguous memory)
for j = 1:cols
for i = 1:rows
A(i,j) = process(i, j);
end
end
% FASTEST - vectorized
[I, J] = ndgrid(1:rows, 1:cols);
A = process(I, J);
Pitfall 4: Unnecessary Data Type Conversions
% SLOW - repeated conversions
for i = 1:n
x = double(data(i));
result(i) = sin(x);
end
% FAST - convert once
x = double(data);
result = sin(x);
Optimization Examples
Example 1: Image Processing
% SLOW
[rows, cols] = size(image);
output = zeros(rows, cols);
for i = 2:rows-1
for j = 2:cols-1
output(i,j) = mean(image(i-1:i+1, j-1:j+1), 'all');
end
end
% FAST
kernel = ones(3,3) / 9;
output = conv2(image, kernel, 'same');
Example 2: Statistical Analysis
% SLOW
n = size(data, 1);
means = zeros(n, 1);
for i = 1:n
means(i) = mean(data(i, :));
end
% FAST
means = mean(data, 2);
Example 3: Time Series Processing
% SLOW
n = length(signal);
movingAvg = zeros(size(signal));
window = 10;
for i = window:n
movingAvg(i) = mean(signal(i-window+1:i));
end
% FAST - trailing window: [window-1 past samples, 0 future samples]
movingAvg = movmean(signal, [window-1 0]);
Troubleshooting Performance
Issue: Code still slow after vectorization
- Solution: Profile to find new bottlenecks; consider algorithm complexity
Issue: Out of memory errors
- Solution: Use smaller data types, process in chunks, use sparse matrices
Issue: parfor slower than for loop
- Solution: Check if overhead outweighs benefits; ensure iterations are expensive enough
Issue: GPU computation slower than CPU
- Solution: Data transfer overhead may exceed computation time; use for large arrays
Additional Resources
- Use
profile viewerto analyze performance - Use
memoryto check memory usage - Use
docwith:timeit,tic/toc,parfor,gpuArray,sparse - Check MATLAB Performance and Memory documentation
MATLAB uihtml App Builder
This skill covers how to build interactive web applications that combine HTML/JavaScript interfaces with MATLAB computational backends using the uihtml component. The HTML side handles the UI; MATLAB does the computation.
When to Use This Skill
- Building interactive MATLAB apps with HTML/JavaScript interfaces
- Creating web-based UIs for MATLAB applications
- Building responsive MATLAB GUIs with HTML/CSS/JS
- When user mentions: uihtml, HTML, JavaScript, web app, web interface, interactive GUI
- Combining web UI design with MATLAB computational power
- Creating calculator apps, data visualizers, or form-based MATLAB tools
Core Architecture
The Four Components
- HTML Interface - User interface with buttons, forms, displays
- JavaScript Logic - Event handling and UI interactions
- MATLAB Backend - Computational engine and data processing
- uihtml Component - Bridge between HTML and MATLAB
Communication Patterns
The uihtml component enables bidirectional communication between JavaScript and MATLAB through several mechanisms:
Pattern 1: MATLAB → JavaScript (Data Property)
Use Case: Sending data from MATLAB to update the HTML interface
% MATLAB side
h.Data = "Hello World!";
// JavaScript side
htmlComponent.addEventListener("DataChanged", function(event) {
document.getElementById("display").innerHTML = htmlComponent.Data;
});
Pattern 2: JavaScript → MATLAB (Events)
Use Case: Triggering MATLAB functions from user interactions
// JavaScript side - send event to MATLAB
htmlComponent.sendEventToMATLAB("Calculate", expression);
% MATLAB side - receive and handle event
h.HTMLEventReceivedFcn = @handleEvent;
function handleEvent(src, event)
eventName = event.HTMLEventName;
eventData = event.HTMLEventData;
% Process event...
end
Pattern 3: MATLAB → JavaScript (Custom Events)
Use Case: Sending computed results or status updates to JavaScript
% MATLAB side - send custom event to JavaScript
sendEventToHTMLSource(h, "ResultChanged", result);
// JavaScript side - listen for custom event
htmlComponent.addEventListener("ResultChanged", function(event) {
document.getElementById("display").textContent = event.Data;
});
Pattern 4: Complex Data Transfer
Use Case: Passing structured data between MATLAB and JavaScript
% MATLAB side - struct data gets JSON encoded automatically
itemData = struct("ItemName","Apple","Price",2,"Quantity",10);
h.Data = itemData;
// JavaScript side - access as object properties
htmlComponent.Data.ItemName // "Apple"
htmlComponent.Data.Price // 2
htmlComponent.Data.Quantity // 10
Important: decoding is automatic in both directions.
- A JS object sent via
sendEventToMATLABarrives onevent.HTMLEventDataalready converted to a MATLAB struct. Do not calljsondecode; it will fail on a struct. - A MATLAB struct sent via
sendEventToHTMLSourcearrives onevent.Dataalready as a JavaScript object. Do not callJSON.parse; it will fail on an object. - Field names round-trip exactly: a JS
{x0: 1}becomes a MATLABstruct('x0', 1), notstruct('x_0', ...)or similar. - Numeric scalars arrive as MATLAB
double. Wrap field reads withdouble(data.x0)if you want to be defensive about types.
Critical Rules
Security Requirements
-
ALWAYS set
HTMLSource = 'trusted'when using local HTML files:h.HTMLSource = fullfile(pwd, 'myapp.html'); % This is treated as trusted automatically for local files -
MUST validate all input from JavaScript before processing in MATLAB
-
NEVER use
eval()on user input without strict sanitization -
ALWAYS restrict allowed characters in user input for expressions
Error Handling
ALWAYS wrap MATLAB event handlers in try-catch blocks:
function handleEvent(src, event)
eventName = event.HTMLEventName;
eventData = event.HTMLEventData;
try
% Process the event
result = processData(eventData);
% Send result back to JavaScript
sendEventToHTMLSource(src, 'ResultEvent', result);
catch ME
% Handle errors gracefully
fprintf('Error: %s\n', ME.message);
sendEventToHTMLSource(src, 'ErrorEvent', ME.message);
end
end
Data Validation
ALWAYS validate user input before processing:
function result = validateExpression(expression)
allowedChars = '0123456789+-*/.() ';
if ~all(ismember(expression, allowedChars))
error('Invalid characters in expression');
end
% Additional validation...
result = true;
end
File Organization
Follow this directory structure:
project/
├── app.m # Main MATLAB function
├── app.html # HTML interface
├── README.md # Usage instructions
└── examples/ # Additional examples (optional)
Complete Examples
Example 1: Simple Calculator App
MATLAB Side (calculator.m):
function calculator()
% Create main figure
fig = uifigure('Name', 'Calculator', 'Position', [100 100 400 500]);
% Create HTML component
h = uihtml(fig, 'Position', [25 25 350 450]);
h.HTMLSource = fullfile(pwd, 'calculator.html');
h.HTMLEventReceivedFcn = @(src, event) handleEvent(src, event);
end
function handleEvent(src, event)
eventName = event.HTMLEventName;
eventData = event.HTMLEventData;
try
switch eventName
case 'Calculate'
% Validate input
expression = char(eventData);
allowedChars = '0123456789+-*/.() ';
if ~all(ismember(expression, allowedChars))
error('Invalid characters in expression');
end
% Evaluate safely
result = eval(expression);
% Send result back
sendEventToHTMLSource(src, 'Result', num2str(result));
case 'Clear'
sendEventToHTMLSource(src, 'Result', '0');
end
catch ME
fprintf('Error: %s\n', ME.message);
sendEventToHTMLSource(src, 'Error', 'Invalid expression');
end
end
HTML Side (calculator.html):
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
margin: 0;
padding: 20px;
}
.calculator {
background: white;
border-radius: 10px;
padding: 20px;
box-shadow: 0 10px 30px rgba(0,0,0,0.3);
}
.display {
width: 100%;
height: 60px;
font-size: 24px;
text-align: right;
padding: 10px;
border: 2px solid #ccc;
border-radius: 5px;
margin-bottom: 10px;
background: #f9f9f9;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
button {
padding: 20px;
font-size: 18px;
border: none;
border-radius: 5px;
cursor: pointer;
background: #667eea;
color: white;
transition: background 0.3s;
}
button:hover {
background: #764ba2;
}
.operator {
background: #ff6b6b;
}
.operator:hover {
background: #ee5a52;
}
</style>
<script type="text/javascript">
let currentExpression = '';
function setup(htmlComponent) {
window.htmlComponent = htmlComponent;
// Listen for results from MATLAB
htmlComponent.addEventListener("Result", function(event) {
document.getElementById("display").value = event.Data;
currentExpression = event.Data;
});
htmlComponent.addEventListener("Error", function(event) {
document.getElementById("display").value = "Error";
currentExpression = '';
});
}
function appendToDisplay(value) {
currentExpression += value;
document.getElementById("display").value = currentExpression;
}
function clearDisplay() {
currentExpression = '';
document.getElementById("display").value = '0';
window.htmlComponent.sendEventToMATLAB("Clear", "");
}
function calculate() {
if (currentExpression) {
window.htmlComponent.sendEventToMATLAB("Calculate", currentExpression);
}
}
</script>
</head>
<body>
<div class="calculator">
<input type="text" id="display" class="display" value="0" readonly>
<div class="buttons">
<button onclick="appendToDisplay('7')">7</button>
<button onclick="appendToDisplay('8')">8</button>
<button onclick="appendToDisplay('9')">9</button>
<button class="operator" onclick="appendToDisplay('/')">/</button>
<button onclick="appendToDisplay('4')">4</button>
<button onclick="appendToDisplay('5')">5</button>
<button onclick="appendToDisplay('6')">6</button>
<button class="operator" onclick="appendToDisplay('*')">*</button>
<button onclick="appendToDisplay('1')">1</button>
<button onclick="appendToDisplay('2')">2</button>
<button onclick="appendToDisplay('3')">3</button>
<button class="operator" onclick="appendToDisplay('-')">-</button>
<button onclick="appendToDisplay('0')">0</button>
<button onclick="appendToDisplay('.')">.</button>
<button onclick="calculate()">=</button>
<button class="operator" onclick="appendToDisplay('+')">+</button>
<button style="grid-column: span 4; background: #ff6b6b;" onclick="clearDisplay()">Clear</button>
</div>
</div>
</body>
</html>
Example 2: Data Visualization App
MATLAB Side (visualizer.m):
function visualizer()
fig = uifigure('Name', 'Data Visualizer', 'Position', [100 100 800 600]);
% Create HTML component for controls
h = uihtml(fig, 'Position', [25 400 750 175]);
h.HTMLSource = fullfile(pwd, 'controls.html');
h.HTMLEventReceivedFcn = @(src, event) handleEvent(src, event, fig);
% Create axes for plotting
ax = uiaxes(fig, 'Position', [25 25 750 350]);
xlabel(ax, 'X');
ylabel(ax, 'Y');
title(ax, 'Interactive Plot');
end
function handleEvent(src, event, fig)
eventName = event.HTMLEventName;
eventData = event.HTMLEventData;
try
switch eventName
case 'UpdatePlot'
% Parse parameters from JavaScript
params = eventData;
frequency = params.frequency;
amplitude = params.amplitude;
plotType = params.plotType;
% Generate data
x = linspace(0, 4*pi, 200);
switch plotType
case 'sine'
y = amplitude * sin(frequency * x);
case 'cosine'
y = amplitude * cos(frequency * x);
case 'both'
y = amplitude * sin(frequency * x);
y2 = amplitude * cos(frequency * x);
end
% Find axes and plot
ax = findobj(fig, 'Type', 'axes');
cla(ax);
if strcmp(plotType, 'both')
plot(ax, x, y, 'LineWidth', 2);
hold(ax, 'on');
plot(ax, x, y2, 'LineWidth', 2);
hold(ax, 'off');
legend(ax, 'Sine', 'Cosine');
else
plot(ax, x, y, 'LineWidth', 2);
end
grid(ax, 'on');
% Send confirmation
sendEventToHTMLSource(src, 'PlotUpdated', 'Success');
end
catch ME
fprintf('Error: %s\n', ME.message);
sendEventToHTMLSource(src, 'Error', ME.message);
end
end
HTML Side (controls.html):
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
color: white;
margin: 0;
padding: 20px;
}
.controls {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 20px;
}
.control-group {
background: rgba(255,255,255,0.1);
padding: 15px;
border-radius: 8px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input[type="range"] {
width: 100%;
}
select, button {
width: 100%;
padding: 8px;
border-radius: 5px;
border: none;
font-size: 14px;
}
button {
background: #3498db;
color: white;
cursor: pointer;
margin-top: 10px;
transition: background 0.3s;
}
button:hover {
background: #2980b9;
}
</style>
<script type="text/javascript">
function setup(htmlComponent) {
window.htmlComponent = htmlComponent;
htmlComponent.addEventListener("PlotUpdated", function(event) {
console.log("Plot updated successfully");
});
}
function updatePlot() {
const frequency = parseFloat(document.getElementById("frequency").value);
const amplitude = parseFloat(document.getElementById("amplitude").value);
const plotType = document.getElementById("plotType").value;
const params = {
frequency: frequency,
amplitude: amplitude,
plotType: plotType
};
window.htmlComponent.sendEventToMATLAB("UpdatePlot", params);
}
function updateFreqLabel(value) {
document.getElementById("freqValue").textContent = value;
}
function updateAmpLabel(value) {
document.getElementById("ampValue").textContent = value;
}
</script>
</head>
<body>
<div class="controls">
<div class="control-group">
<label>Frequency: <span id="freqValue">1</span></label>
<input type="range" id="frequency" min="0.1" max="5" step="0.1" value="1"
oninput="updateFreqLabel(this.value)">
</div>
<div class="control-group">
<label>Amplitude: <span id="ampValue">1</span></label>
<input type="range" id="amplitude" min="0.1" max="5" step="0.1" value="1"
oninput="updateAmpLabel(this.value)">
</div>
<div class="control-group">
<label>Plot Type:</label>
<select id="plotType">
<option value="sine">Sine</option>
<option value="cosine">Cosine</option>
<option value="both">Both</option>
</select>
</div>
</div>
<button onclick="updatePlot()">Update Plot</button>
</body>
</html>
Example 3: Form Processing App
MATLAB Side (formProcessor.m):
function formProcessor()
fig = uifigure('Name', 'Form Processor', 'Position', [100 100 600 400]);
h = uihtml(fig, 'Position', [25 25 550 350]);
h.HTMLSource = fullfile(pwd, 'form.html');
h.HTMLEventReceivedFcn = @(src, event) handleEvent(src, event);
end
function handleEvent(src, event)
eventName = event.HTMLEventName;
eventData = event.HTMLEventData;
try
switch eventName
case 'SubmitForm'
% Extract form data
name = eventData.name;
email = eventData.email;
age = eventData.age;
% Validate data
if isempty(name) || isempty(email)
error('Name and email are required');
end
if ~contains(email, '@')
error('Invalid email address');
end
if age < 0 || age > 120
error('Invalid age');
end
% Process data (example: save to file or database)
fprintf('Processing form:\n');
fprintf(' Name: %s\n', name);
fprintf(' Email: %s\n', email);
fprintf(' Age: %d\n', age);
% Send success message
result = struct('status', 'success', ...
'message', 'Form submitted');
sendEventToHTMLSource(src, 'FormResult', result);
case 'ClearForm'
sendEventToHTMLSource(src, 'FormCleared', '');
end
catch ME
fprintf('Error: %s\n', ME.message);
result = struct('status', 'error', 'message', ME.message);
sendEventToHTMLSource(src, 'FormResult', result);
end
end
Best Practices
UI Design Principles
The HTML in the examples below is deliberately minimal to keep the focus on the MATLAB↔JS wiring. The inline styling (Arial,
#667eea → #764ba2purple-blue gradients, generic cards) is not a design reference. Those are exactly the "AI slop" tells to avoid. For any panel a user will actually see, take the visual system frommatlab-uihtml-designand follow its Design Guardrails.
- Use CSS Grid or Flexbox for responsive layouts that adapt to different window sizes. Flexbox for 1D, Grid for 2D; don't default to Grid when
flex-wrapis simpler - Implement hover effects for better user experience and visual feedback
- Provide clear visual feedback for user actions (button clicks, form submission, errors), plus a visible
:focus-visiblestate for keyboard users - Use semantic HTML elements (button, input, form) for better accessibility
- Pick a color scheme deliberately (see
matlab-uihtml-designfor ready-made styles). Avoid the default reflexes: Inter/Roboto/Arial fonts, purple-to-blue gradients, side-stripeborder-leftaccents, gradient text, and over-rounded (≥32px) cards - Verify contrast: body/label text ≥4.5:1, large text and UI boundaries ≥3:1. Give numeric readouts
font-variant-numeric: tabular-numsso values don't jitter width - Respect reduced motion: wrap non-essential animation in
@media (prefers-reduced-motion: reduce)with a crossfade/instant fallback
Performance Optimization
- Minimize data transfer between HTML and MATLAB - send only necessary data
- Use appropriate data types - numbers, strings, structs (converted to JSON)
- Implement loading indicators for long MATLAB operations
- Cache results when appropriate using persistent variables in MATLAB
- Batch multiple updates instead of sending many small events
Error Handling Strategy
JavaScript Side:
htmlComponent.addEventListener("Error", function(event) {
// Display user-friendly error messages
alert("Error: " + event.Data);
});
MATLAB Side:
try
result = processInput(input);
sendEventToHTMLSource(src, 'Success', result);
catch ME
fprintf('Error: %s\n', ME.message);
sendEventToHTMLSource(src, 'Error', 'Processing failed');
end
Testing Strategy
-
Unit Testing - Test MATLAB functions independently
% Test individual processing functions assert(validateExpression('2+2'), 'Validation should pass'); -
Integration Testing - Test HTML-MATLAB communication
% Test event handling with sample data testEvent = struct('HTMLEventName', 'Calculate', 'HTMLEventData', '2+2'); handleEvent(h, testEvent); -
User Testing - Test complete user workflows
- Try all button combinations
- Test edge cases and invalid inputs
- Verify visual feedback is clear
-
Error Testing - Test error conditions
- Invalid input characters
- Empty input fields
- Network/timeout scenarios
Debugging Tips
-
MATLAB Side: Use
fprintf()to log events and datafprintf('Received event: %s with data: %s\n', eventName, eventData); -
JavaScript Side: Use browser developer tools (F12) to debug
console.log("Sending to MATLAB:", data); -
Test each communication direction separately
- First test MATLAB → JavaScript (Data property)
- Then test JavaScript → MATLAB (events)
- Finally test bidirectional flow
-
Verify data types and formats
fprintf('Data type: %s\n', class(eventData)); fprintf('Data value: %s\n', string(eventData));
Common Patterns
Pattern 1: Calculator Pattern
- JavaScript builds expression strings from button clicks
- Send expression to MATLAB via
sendEventToMATLAB - MATLAB safely evaluates with input validation
- Results sent back via
sendEventToHTMLSource - Display results in real-time
Pattern 2: Data Visualization Pattern
- JavaScript handles user interaction (sliders, dropdowns)
- Send parameters to MATLAB for computation
- MATLAB processes data and updates plots
- Can use uiaxes for MATLAB plots or send data for JavaScript plotting
- Support real-time updates and animations
Pattern 3: Form Processing Pattern
- JavaScript collects form data into structured object
- Send entire form data as single event
- MATLAB validates each field
- Process data (save, compute, export)
- Send confirmation or error messages back
- Update UI based on results
Pattern 4: Real-time Monitoring Pattern
- MATLAB continuously generates data (simulation, sensor reading)
- Send updates via
sendEventToHTMLSourceat intervals - JavaScript updates display in real-time
- Implement start/stop/pause controls
- Use efficient data formats (arrays, structs)
Long-Running Operations
When MATLAB drives an operation that takes more than a fraction of a second (an animation, an integration sweep, a streaming simulation), the patterns above need a few additions: a timer, resource cleanup, a way to cancel, and a way to tune the operation while it runs.
Timer-Driven Animation
Use a MATLAB timer to drive the operation. Store the handle on fig.UserData so other event handlers (Reset, Stop, figure-close) can find and stop it.
function startAnimation(fig, ax, data)
stopAnimTimer(fig); % kill any prior run
state.data = data;
state.idx = 1;
state.line = animatedline(ax, 'Color', [0.65 0.55 0.94], 'LineWidth', 1.4);
state.step = 5; % points per tick (mutable from outside; see below)
tmr = timer( ...
'ExecutionMode', 'fixedSpacing', ...
'Period', 0.03, ...
'BusyMode', 'drop', ... % skip ticks if callback overruns
'TimerFcn', @(s, ~) animStep(s, fig));
tmr.UserData = state;
fig.UserData.AnimTimer = tmr;
start(tmr);
end
function animStep(tmr, fig)
if ~isvalid(fig) || ~isvalid(tmr), return; end
s = tmr.UserData;
iEnd = min(numel(s.data), s.idx + s.step - 1);
addpoints(s.line, s.data(s.idx:iEnd, 1), s.data(s.idx:iEnd, 2));
s.idx = iEnd + 1;
tmr.UserData = s;
drawnow limitrate;
if s.idx > numel(s.data)
stop(tmr); delete(tmr);
fig.UserData.AnimTimer = [];
% Notify JS that the operation completed
sendEventToHTMLSource(fig.UserData.UIHtml, 'OperationDone', struct('n', iEnd));
end
end
Key choices:
BusyMode='drop': if a callback takes longer thanPeriod, the next tick is skipped rather than queued. This prevents callback pile-ups on slow systems.drawnow limitrate: caps rendering at ~20 fps while still processing UI events, so the user can still interact (scroll, drag sliders, click Stop).- Self-cleaning: the last tick stops and deletes the timer, then nulls out the stored handle.
Resource Cleanup on Figure Close
Any timer, listener, or background resource must be torn down when the figure closes. Otherwise it leaks across reruns and can fire callbacks against deleted graphics objects.
fig.UserData = struct('AnimTimer', [], 'UIHtml', h, 'Axes', ax);
fig.CloseRequestFcn = @(s, ~) closeFig(s);
function closeFig(fig)
stopAnimTimer(fig);
delete(fig);
end
function stopAnimTimer(fig)
if ~isvalid(fig) || ~isfield(fig.UserData, 'AnimTimer'), return; end
tmr = fig.UserData.AnimTimer;
if ~isempty(tmr) && isvalid(tmr)
try, stop(tmr); catch, end
delete(tmr);
end
fig.UserData.AnimTimer = [];
end
The same stopAnimTimer is reused by Reset and Stop handlers, so there's one cleanup path to maintain.
Cancellable Operations (Run ↔ Stop)
For operations the user might want to cancel, repurpose the primary action button via a JS state machine. Don't add a separate Stop button; the panel gets crowded, and a context-aware single button matches play/pause UX.
// JS state machine
let runState = "idle"; // 'idle' | 'running' | 'cancellable'
function setRunning(state) {
runState = state;
const b = document.getElementById("runBtn");
b.classList.remove("busy");
if (state === "idle") {
b.textContent = "Run";
b.disabled = false;
} else if (state === "running") { // brief, non-cancellable
b.textContent = "Run";
b.classList.add("busy");
b.disabled = true;
} else if (state === "cancellable") { // long, user can stop
b.textContent = "Stop";
b.classList.add("busy");
b.disabled = false;
}
}
function onRunClick() {
if (runState === "cancellable") {
window.htmlComponent.sendEventToMATLAB("StopOperation", "");
return;
}
setRunning("cancellable");
window.htmlComponent.sendEventToMATLAB("RunOperation", collectParams());
}
On the MATLAB side, StopOperation stops the timer, leaves any partial output in place (so the user keeps what was computed), and emits an event so JS can flip the button back to "Run":
case 'StopOperation'
stopAnimTimer(fig);
s = lastState(fig); % whatever partial result you tracked
sendEventToHTMLSource(src, 'OperationStopped', s);
Distinguish three completion events back to JS:
| Event | When |
|---|---|
OperationDone | Natural completion (full result) |
OperationStopped | User clicked Stop (partial result) |
OperationError | Caught exception (error message) |
All three should call setRunning("idle") in JS so the button returns to "Run".
Live Control During an Ongoing Operation
When the user wants to tune a parameter while the operation runs (animation speed, simulation rate, plot range), the JS slider's input event needs to push updates to MATLAB without restarting the operation.
Two rules:
-
Throttle the JS-side send so dragging the slider doesn't flood MATLAB with events:
let sendTimer = null; document.getElementById("speed").addEventListener("input", function() { if (sendTimer) return; sendTimer = setTimeout(function() { const v = parseInt(document.getElementById("speed").value, 10); window.htmlComponent.sendEventToMATLAB("SetSpeed", v); sendTimer = null; }, 80); // ~12 events/sec max }); -
Patch the live timer's
UserDatain place. Don't stop and restart:case 'SetSpeed' tmr = fig.UserData.AnimTimer; if ~isempty(tmr) && isvalid(tmr) s = tmr.UserData; s.step = max(1, min(50, round(double(data)))); % clamp + sanitize tmr.UserData = s; end % no-op if no animation running; the slider still updates its label
MATLAB serializes all callbacks on the main thread, so the timer tick and the SetSpeed handler never execute concurrently. The UserData update is atomic from the tick's point of view.
Saving the Output (Export from a uiaxes)
A common requirement: a "Save Image" button in the HTML that exports the current plot. Use uiputfile + exportgraphics:
case 'ExportImage'
ax = fig.UserData.Axes;
if isempty(ax.Children)
sendEventToHTMLSource(src, 'ExportError', 'Nothing to export');
return;
end
defaultName = sprintf('plot_%s.png', string(datetime('now', 'Format', 'yyyyMMdd_HHmmss')));
[file, path] = uiputfile({'*.png';'*.jpg';'*.pdf'}, 'Export plot', defaultName);
if isequal(file, 0)
sendEventToHTMLSource(src, 'ExportComplete', 'cancelled');
return;
end
try
exportgraphics(ax, fullfile(path, file), 'Resolution', 300, ...
'BackgroundColor', fig.Color);
sendEventToHTMLSource(src, 'ExportComplete', file);
catch ME
sendEventToHTMLSource(src, 'ExportError', ME.message);
end
Pass fig.Color as BackgroundColor so the export matches the on-screen figure background. Important for dark themes, where the default white background looks wrong.
Implementation Checklist
Before deploying a uihtml app, verify:
- HTML file exists in correct location
-
HTMLSourceproperty set to correct file path -
HTMLEventReceivedFcncallback defined - JavaScript
setup(htmlComponent)function implemented - Event listeners added for MATLAB→JS communication
- Try-catch blocks wrap all MATLAB event handling
- Input validation implemented for all user data
- Error events sent back to JavaScript for user feedback
- CSS styling applied consistently (see
matlab-uihtml-design), free of AI-slop tells (purple-blue gradients, side-stripe borders, gradient text, over-rounded cards, generic Arial/Inter) - Contrast verified (body/label ≥4.5:1, large text and UI boundaries ≥3:1)
- Reduced-motion fallback present (
@media (prefers-reduced-motion: reduce)) - Keyboard focus is visible (
:focus-visible), not removed with a bareoutline: none - Responsive design tested at different window sizes
- All user interactions provide visual feedback
- Loading indicators shown for long operations
- File organization follows project structure
- Documentation (README) created with usage instructions
- Resource cleanup wired to
CloseRequestFcn: anytimer, listener, or background task is stopped and deleted when the figure closes. Without this, callbacks fire against deleted graphics after the user closes the app. - Long operations are cancellable: if the operation can run more than ~1 second, the user can stop it without killing the figure.
Troubleshooting
Issue: HTML file not loading in uihtml component
- Solution: Check file path is absolute or relative to current directory
h.HTMLSource = fullfile(pwd, 'app.html'); % Absolute path
Issue: Events not triggering MATLAB callback
- Solution: Verify
HTMLEventReceivedFcnis set before HTML loads - Solution: Check JavaScript is calling
sendEventToMATLABcorrectly
Issue: Data not updating in JavaScript
- Solution: Ensure
DataChangedevent listener is registered insetup() - Solution: Verify MATLAB is setting
h.Dataproperty, not sending event
Issue: JavaScript errors in browser console
- Solution: Open browser dev tools (F12) to see detailed error messages
- Solution: Ensure
htmlComponentis passed tosetup()function - Solution: Check for typos in element IDs and function names
Issue: MATLAB errors not displayed to user
- Solution: Implement error event handling in both MATLAB and JavaScript
- Solution: Use try-catch in MATLAB and send error messages via
sendEventToHTMLSource
Issue: Slow performance when sending data
- Solution: Reduce frequency of updates (throttle events)
- Solution: Send only changed data, not entire datasets
- Solution: Use appropriate data types (numbers vs strings)
Issue: Complex data structures not transferring correctly
- Solution: Use MATLAB structs (automatically converted to JSON)
- Solution: Avoid nested cell arrays; use struct arrays instead
- Solution: Test data transfer with simple examples first
Issue: Styling not appearing correctly
- Solution: Verify CSS is in
<style>block inside<head> - Solution: Check for CSS syntax errors
- Solution: Use browser dev tools to inspect computed styles
Additional Resources
- MATLAB Documentation:
doc uihtml - HTML/CSS/JavaScript: MDN Web Docs
- Event handling:
doc sendEventToHTMLSource - Figure creation:
doc uifigure - Debugging: Use browser Developer Tools (F12)
Related Skills
- matlab-uihtml-design: visual design styles (Clean, Material, Cosmic Dark, etc.) with ready-to-use HTML templates and design specs. Use it to style your uihtml controls.
MATLAB uihtml Design Skill
Generate production-grade HTML/CSS/JS control panels for MATLAB uihtml components with distinctive, configurable visual styles.
When to Use
- User wants beautiful custom controls in a MATLAB app via
uihtml - User asks for a specific design style (Clean, Material, dark theme, etc.)
- User wants to redesign or restyle existing
uihtmlcontrols - User describes a custom aesthetic for their MATLAB app controls
Style Selection
Built-in styles are documented in references/design-styles.md. To apply a style:
-
If the user names a built-in style, read the corresponding file from
references/styles/<name>.md -
If the user describes a custom aesthetic, apply creative design thinking (see below) without loading a reference style
-
If no style is specified, open the visual style gallery in the user's browser so they can see all 8 styles side-by-side:
start "" "<skill-directory>/assets/style-gallery.html" # Windows open "<skill-directory>/assets/style-gallery.html" # macOSThen ask: "I've opened the style gallery in your browser. Which style would you like? You can also describe a custom aesthetic."
The gallery shows interactive previews of all 8 built-in styles with a Dark/Light toggle. The available styles are:
Style Vibe Clean Frosted glass, depth layers, spring animations Material Tonal surfaces, elevation, rounded shapes Cosmic Dark Deep space, neon glow, glassmorphism Neumorphic Dark Embossed/debossed, soft shadow pairs Dashboard Light White cards, indigo accent, data-dense Midnight Gradient Blue-to-purple gradients, luxury glow Minimal Mono Ultra-flat, pill buttons, single accent Warm Dark Amber/yellow accent, friendly, smart home If the user says "just pick one" or wants to move fast, default to Clean.
Each style reference follows the 9-section DESIGN.md format and provides complete specifications for colors, typography, components, motion, and guardrails.
Design Thinking
Before generating code, commit to a clear aesthetic direction:
- Purpose: What does this control panel do? Who uses it?
- Tone: What feeling should the interface evoke?
- Constraints: Container size, MATLAB integration requirements, offline (no CDN)
- Differentiation: What makes this memorable and cohesive?
Execute the chosen direction with precision. Bold maximalism and refined minimalism both work, as long as the choice is intentional.
Workflow
- Style selection: Identify or create the aesthetic direction
- Component planning: Determine which controls are needed (sliders, buttons, toggles, etc.)
- HTML generation: Produce self-contained HTML with the chosen style applied
- MATLAB integration: Include
setup(htmlComponent)boilerplate; defer full MATLAB-side wiring to thematlab-uihtml-app-builderskill
Component Library (v1)
Sliders
- Range inputs with custom thumb and track styling
- Value display with formatted units
- Horizontal layout with label + value header
Buttons
- Primary/Filled: Bold accent color, prominent shadow/glow
- Secondary/Outlined: Transparent with border, subtle hover
- Destructive/Danger: Warning color for stop/reset actions
- State: default, hover, focus-visible, active (scale 0.97), disabled (see the Interactive states table in Design Guardrails)
Toggles
- Sliding toggle switches
- On/off states with color transition
- Keyboard-operable (focusable, toggle on Space/Enter) with accessible click/tap targets
Theme System
All styles use CSS custom properties for theming. The base architecture:
:root {
/* Semantic colors, filled by chosen style */
--color-bg-primary: ...;
--color-bg-secondary: ...;
--color-bg-surface: ...;
--color-accent: ...;
--color-accent-hover: ...;
--color-text-primary: ...;
--color-text-secondary: ...;
--color-border: ...;
/* Spacing */
--space-xs: 4px;
--space-sm: 8px;
--space-md: 16px;
--space-lg: 24px;
/* Typography */
--font-family: ...;
--font-size-sm: ...;
--font-size-md: ...;
--font-size-lg: ...;
/* Radii & Shadows */
--radius-sm: ...;
--radius-md: ...;
--shadow-sm: ...;
--shadow-md: ...;
/* Motion */
--transition-fast: ...;
--transition-med: ...;
}
Support both light and dark modes via prefers-color-scheme media query or a data-theme attribute on <html>:
@media (prefers-color-scheme: dark) { ... }
/* or */
[data-theme="dark"] { ... }
Container-Aware Spacing
uihtml containers in MATLAB apps are often height-constrained (e.g., a narrow side panel). When applying any style:
- Read the existing HTML first to understand how many controls need to fit
- Prioritize fitting all controls over matching the style's ideal spacing. Reduce padding, gaps, and font sizes as needed; the neumorphic effect still works at 16px padding and 16px gaps
- Use compact variants when the container holds more than 2 panels: body padding 14px, panel padding 16px, inter-panel gap 16px, button padding 9px 18px
- Padding has a floor. Even when compacting, keep ~12px of padding inside a bordered or tinted panel (8px absolute minimum). Trim inter-panel gaps and font sizes before you starve the panel's own padding. Text or controls flush against a panel edge read as cramped and unfinished
- Never let content overflow: if
overflow: hiddenis set on the body, clipped controls are invisible and unusable - Test mentally: count the vertical space budget (panels × padding + gaps + content height) and ensure it fits within a typical side-panel height (~400–500px)
Scrollable Panels (When Content Exceeds the Container)
When the control set genuinely can't be compacted further (4+ panels, mixed sliders + toggles + buttons), make the panel container scroll instead of clipping. Keep body non-scrolling so the background gradient stays anchored, and let the inner .app (or whatever you named the flex column) scroll:
html, body {
overflow: hidden; /* body never scrolls; background gradient stays put */
}
.app {
height: 100%;
overflow-y: auto;
overflow-x: hidden;
scrollbar-width: thin; /* Firefox */
scrollbar-color: rgba(255, 255, 255, 0.12) transparent; /* Firefox */
}
/* Chromium (uihtml uses CEF/Chromium) */
.app::-webkit-scrollbar { width: 6px; }
.app::-webkit-scrollbar-track { background: transparent; }
.app::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.10);
border-radius: 3px;
transition: background var(--t-fast);
}
.app::-webkit-scrollbar-thumb:hover { background: var(--accent-glow); }
Adapt the colors to the chosen palette:
| Style | Thumb default | Thumb hover |
|---|---|---|
| Dark styles (Cosmic Dark, Midnight Gradient, Neumorphic Dark, Warm Dark, Minimal Mono) | rgba(255,255,255,0.10) | var(--accent-glow) |
| Light styles (Clean, Dashboard Light, Material light mode) | rgba(0,0,0,0.12) | rgba(0,0,0,0.22) or var(--accent) |
Keep the scrollbar 6px wide and the thumb under 20% alpha; anything heavier breaks the style. Don't show track borders or arrows.
Design Guardrails
These are cross-cutting rules that apply on top of whatever style is chosen. They exist to keep generated control panels from reading as "AI made that." A named built-in style that deliberately uses one of these moves as its identity (Cosmic Dark's neon glow, Midnight Gradient's blue-to-purple, Clean's glass) is intentional voice and is fine. The guardrails target the unconscious reflex of reaching for these on every panel.
Contrast (verify, don't eyeball)
- Body and label text must hit ≥4.5:1 against its background; large or bold text (≥18px, or ≥14px bold) needs ≥3:1. UI component boundaries, slider tracks, toggle outlines, and icons also need ≥3:1.
- Value readouts and placeholder text need the full 4.5:1 too: don't let a "tertiary" gray slip below it just because it's secondary information. The single most common failure is muted gray text on a tinted near-white (light styles) or a low-contrast gray on near-black (dark styles). If contrast is even close, push the text toward the ink end of the ramp.
- Gray text on a colored surface looks washed out. On an accent-colored button or panel, don't use neutral gray for the label: use white/near-white, a darker shade of the surface's own hue, or an alpha of the text color.
Numeric readouts
- Slider value displays, counters, and any aligned numbers get
font-variant-numeric: tabular-numsso the width doesn't jitter as digits change while dragging.
Motion
-
Reduced motion is not optional. Every non-trivial transition or entrance animation needs a
@media (prefers-reduced-motion: reduce)fallback, typically a crossfade or an instant state change. Include this in the template's<style>block:@media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; } } -
Reveal/entrance animations must enhance an already-visible default. Don't gate a control's visibility on a class-triggered transition. Inside
uihtml(a headless Chromium/CEF render) a transition that never fires ships the panel blank. -
Timing. A control panel is a task UI: no page-load choreography; users are here to do something and won't wait for it. Durations: 100–150ms for instant feedback (press, toggle, value change), 200–300ms for state changes (menu open, panel expand). Keep interactive feedback under ~200ms so it feels instant. Run exit transitions at ~75% of their entrance duration.
-
Easing. Ease out with an exponential curve; never bounce or elastic. Define one as a token and reuse it:
--ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); /* smooth */ --ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1); /* snappier */ --ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1); /* decisive */A subtle spring/compression on a control press is fine; a bouncy elastic entrance applied uniformly to every panel is a tell.
-
Animate
transform/opacity/filter, not layout properties (width, height, top, margin).
Structure & interaction
- Panels are this skill's "cards": never nest a panel inside a panel. Group related controls in one panel; separate groups with spacing or a hairline, not a second layer of container.
- Dropdowns and custom menus get clipped by the container. Because
uihtmlpanels frequently setoverflow: hiddenoroverflow: auto(see Scrollable Panels above), aposition: absolutemenu inside them is cut off. The reliable fix acrossuihtml's embedded Chromium isposition: fixedwith coordinates computed from the trigger'sgetBoundingClientRect()(flip above / left when near a viewport edge). Native<dialog>+showModal()(top layer) also escapes clipping. The Popover API and CSS anchor positioning are cleaner but need a recent Chromium. Only rely on them if you've confirmed the installed MATLAB'suihtmlrenderer supports them; otherwise fall back toposition: fixed. - Provide a visible
:focus-visiblestate for keyboard users: ≥3:1 against adjacent colors, 2–3px, offset outside the element. A box-shadow ring oroutline+outline-offsetboth work; never shipoutline: nonewith no replacement. - Build a small semantic z-index scale (e.g. dropdown → sticky → modal → tooltip) rather than arbitrary
999/9999.
Interactive states
Every control needs its states designed, not just the default. Keyboard users never see :hover, so focus is separate from hover and is not optional.
| State | Applies to | Treatment |
|---|---|---|
| Default / hover / active | all controls | base; subtle lift or color shift on hover; press feedback (e.g. transform: scale(0.97)) on active |
| Focus | all controls | visible :focus-visible ring per the rule above |
| Disabled | buttons, inputs | reduced opacity, cursor: not-allowed, no hover response |
| Loading / busy | actions that call MATLAB | spinner, pulse, or a busy-styled button; a long MATLAB op (>~1s) should show progress and stay cancellable |
| Error / success | status feedback | color plus an icon or text message, never color alone |
Loading / error / success are usually driven from the MATLAB backend; see matlab-uihtml-app-builder for the event wiring (e.g. SimComplete / SimError, busy-button state machine).
Refuse-and-rewrite (AI-slop tells)
If you're about to write any of these, restructure instead:
-
Side-stripe accents: a thick colored bar down one edge of a panel, list row, callout, or alert. This is never the right answer; it reads instantly as "AI made that." It shows up in several disguises, and the ban covers all of them:
/* ❌ all of these render the same orange side-stripe */ .panel { border-left: 4px solid var(--accent); } /* the obvious one */ .panel { border-inline-start: 3px solid var(--accent); } /* logical-property alias */ .panel { box-shadow: inset 4px 0 0 var(--accent); } /* inset shadow, no `border-left` in sight */ .panel { border-width: 1px 1px 1px 4px; border-color: … var(--accent); } /* asymmetric border widths */ .panel::before { content: ''; position: absolute; left: 0; width: 4px; height: 100%; background: var(--accent); } /* ✅ mark state another way */ .panel[data-state="active"] { border: 1px solid var(--accent); } /* full hairline border */ .panel[data-state="active"] { background: var(--accent-soft); } /* an ~8% accent wash, defined as a token */ .panel[data-state="active"] .title::before { content: '● '; color: var(--accent); } /* leading glyph */Rule of thumb: any left/right border wider than 1px, or any accent-colored fill narrower than ~8px running the full height of one edge, is a side-stripe. Rewrite it.
-
Gradient text:
background-clip: textover a gradient. Emphasize with weight, size, or a single solid color. -
Ghost-card: a 1px border and a soft wide
box-shadow(blur ≥16px) on the same element. Pick one: a defined border, or a shadow at ≤8px blur. -
Over-rounding:
border-radius≥32px on panels or inputs. Panels top out around 12–16px; full-pill radius is only for tags and buttons. -
Cream/sand/beige body backgrounds by reflex and default purple-blue gradients or dark glows as generic decoration. If the chosen style doesn't call for them, don't add them.
Microcopy
Panel text is part of the design. Slop in a label or a status line reads as "AI made that" as loudly as a side-stripe does. These are engineer-facing MATLAB tools, so write like the product does: declarative, plain, and trusting the reader's competence.
- Labels & section headers are noun phrases, never questions or hype: "Initial Conditions", "Parameters", "Last Result", not "Ready to simulate?" or "Let's get started".
- Buttons are functional imperatives: "Run", "Reset", "Export PNG", "Stop". No exclamation points, no urgency, no emoji.
- Status, empty, and error messages state what happened, plainly: "Trajectory rendered (4449 pts)", "Nothing to export", "Invalid expression", not "Oops! Something went wrong 🎉" or "Success!".
- No slop words anywhere in UI text: leverage, unlock, seamless, powerful, streamline, supercharge, cutting-edge (and "robust" unless it means an actual engineering tolerance). No em dashes in microcopy: use a colon, comma, or period.
- Trust the engineer: don't gloss terms the audience already knows (σ, ρ, β, "attractor" need no explanation).
MATLAB-driven status text (wired in matlab-uihtml-app-builder) follows the same rules: the string that MATLAB sends to a status line is microcopy too.
Conventions
- Self-contained: No external CDN links; all CSS and JS inline in a single HTML file
- Responsive: Must work within arbitrary
uihtmlcontainer sizes; use flexbox/grid with relative units - MATLAB event boilerplate: Always include the
setup(htmlComponent)function pattern:
function setup(htmlComponent) {
window.htmlComponent = htmlComponent;
// Listen for events from MATLAB
htmlComponent.addEventListener("EventName", function(event) {
// Handle event.Data
});
// Send events to MATLAB
htmlComponent.sendEventToMATLAB("EventName", { key: value });
}
- Theme sync with MATLAB desktop: All templates listen for a
SetThemeevent. The MATLAB side can detect the desktop theme and push it to the HTML component. Thesettingspath is R2025a+, so wrap it in try/catch with a sensible default so the app still works on older releases:
% Detect MATLAB desktop theme (R2025a+); fall back to a default on older releases
themeStr = 'dark'; % or 'light', whichever the style is designed for
try
s = settings;
themeStr = lower(char(s.matlab.appearance.MATLABTheme.ActiveValue));
catch
% settings.matlab.appearance not available on this release; keep the default
end
sendEventToHTMLSource(htmlComp, "SetTheme", struct("theme", themeStr));
The HTML setup() function already includes a SetTheme listener that sets data-theme on the root element, triggering the CSS variable swap.
-
Fonts: For a dense app UI a native system stack (
-apple-system, 'Segoe UI', system-ui, sans-serif) is a legitimate, fast, offline-safe default. The built-in templates use one, and it's the right call for control panels. What reads as "AI made that" is reaching for a distinctive-but-overused display face for personality: Inter, Roboto, Geist, Space Grotesk, Plus Jakarta Sans, Fraunces (and plain Arial). Avoid those. If you pair fonts, pair on a real contrast axis (serif + sans); don't pair two similar sans-serifs. Also avoid purple-on-white cliches and cookie-cutter layouts; see the refuse-and-rewrite list in Design Guardrails above -
Accessible: Meet the contrast, focus-visible, interactive-states, and reduced-motion requirements in Design Guardrails above. Keep targets comfortably clickable (~28px+ hit area for toggles/thumbs, larger for buttons; size up toward 44px if the app may run on a touch display)
-
Performance: CSS-only animations preferred; minimize JavaScript for visual effects
-
External links:
<a href="…" target="_blank" rel="noopener">opens in the system default browser fromuihtml, not inside the MATLAB figure. Useful for "view docs / view source" links in the app header. Style the link to fit the palette (accent color on hover, no underline by default):.external-link { color: var(--text-secondary); text-decoration: none; transition: color var(--t-fast), text-shadow var(--t-fast); } .external-link:hover { color: var(--accent-secondary); text-shadow: 0 0 8px var(--accent-glow); /* dark styles */ }
Related Skills
- matlab-uihtml-app-builder: architecture, communication patterns, event handling, and MATLAB backend integration for uihtml apps. Use it for the functional wiring behind your styled controls.
Simulink Test Sequences from EARS Requirements
Map requirement phrases to model signals, review the mappings, and generate Test Sequence harnesses with the bundled MATLAB helpers.
Core rules
- Start with a YAML mapping review. Use an existing explicit approval when available; do not infer approval from a filename or from a mapping appearing obvious.
- Scope the review and generation to the requested requirement IDs.
- Resolve open questions about signals, units, enum values, precondition paths,
and timing before generating tests. Include complete initialization,
stimulus, and
verify()statements. - Associated harness creation saves registration metadata on the owner model. Use a writable working copy for demos. Explain this effect when preparing generation against a user's model.
- Inspect per-requirement warnings and compile results. The generator can
continue after a harness fails; the final completion message and presence of
a
.slxfile do not establish success. - Compilation is not test execution. Run the generated test when requested, and distinguish a compile check from simulation and assertion results.
Setup and inputs
Identify the model under test, the .slreqx requirement set, and any
.sldd dictionaries or enumeration classes. Resolve the folder containing
this file as skillRoot, then add fullfile(skillRoot, "scripts") to the
MATLAB path.
Run MATLAB from the model artifacts folder (or set the evaluation tool's
working-folder option). Discovery scans that folder for dictionaries and enum
classes. Verify which("analyzeRequirements") resolves to this installation.
The older analizeRequirements spelling remains a compatibility alias.
Phase 1: Review the mappings
Use analyzeRequirements(modelName, reqSetPath) for requirement and model
discovery. For a review of selected requirements:
review = generateMappingReviewFromRequirements( ...
'ModeLogic', 'HLR_ModeLogic_EARS.slreqx', ...
'mapping_review_req17.yaml', 'RequirementIds', "17");
Read workflow-details.md when constructing or
editing the YAML. Lead with phrase_mappings containing the requirement
phrase, model element, and interpretation. Keep generation fields in the same
file: init_assignments, precondition_path, stimulus_assignments, and
verify_statements.
Record assumptions in test_assumptions, unresolved meanings in
open_questions, and approval in status. Show the final review file in
the MATLAB Editor when available, unless the user requests otherwise. For
headless operation or intermediate files, pass 'OpenInEditor', false.
Present a short mapping summary and request review when approval is missing.
After the user approves, set the accepted entries to status: 'approved'.
Edits with unresolved questions do not constitute approval.
Phase 2: Generate and inspect
result = buildHarnessesFromApprovedYaml( ...
'ModeLogic', 'mapping_review_req17.yaml');
The default creates externally saved harnesses in test_harnesses/ and
registers them on the source model. If the requested output is standalone
harness files, the staged alternative is:
result = buildHarnessesFromApprovedYaml( ...
'ModeLogic', 'mapping_review_req17.yaml', ...
'AssociateWithSourceModel', false);
That alternative generates in a temporary workspace and copies harness files back; it does not register them on the source model. Inspect the reported build folder when troubleshooting dictionary or model shadowing.
Open the generated harness and relevant result.test_sequence_blocks when
a desktop session is available and the user has not requested headless work.
Use the returned paths to inspect the Test Sequence. Do not recreate the
bundled helpers.
Supported patterns and limits
| EARS pattern | Form | Generated steps |
|---|---|---|
| Ubiquitous | The system shall ... | Initialize and verify |
| Event-driven | When ..., the system shall ... | Establish preconditions, trigger, verify |
| State-driven | While ..., the system shall ... | Establish the state and check behavior |
| Unwanted behavior | If ..., then the system shall ... | Apply the condition and check the response |
| Optional | Where ..., the system shall ... | Use the event-driven configurator |
The parser recognizes these sentence forms; arbitrary natural-language requirements may need clarification. Automated phrase and precondition inference includes ModeLogic-specific heuristics, so review mappings against the actual system. The bundled timing defaults and one scenario per requirement do not establish exhaustive verification.
Requirements Toolbox traceability links must be added separately through Simulink Test Manager. Do not claim certification, standards compliance, or complete requirement coverage from generated harnesses.
Supporting functions
Workflow details includes the YAML schema,
a ModeLogic example, the low-level signalMappings struct, and the helper
catalog. Use it for custom mappings and multi-step preconditions.
Copyright 2026 The MathWorks, Inc.
Sponsors
Details
- Marketplace
- matlab/skills
- Author
- The MathWorks, Inc.
- Category
- Community
- License
- BSD-3-Clause
- Keywords
- matlab, live-scripts, testing, performance, optimization, vectorization, code-generation, scientific-computing, data-analysis, programming, html, javascript, uihtml, web, interactive, gui, webapp, filter, digital-filter, signal-processing, fir, iir, lowpass, highpass, bandpass, bandstop, notch, dsp