Optimize MATLAB code for better performance through vectorization, memory management, and profiling. Use when user requests optimization, mentions slow code, performance issues, speed improvements, or asks to make code faster or more efficient.
View on GitHubSelect agents to install to:
npx add-skill https://github.com/matlab/skills/blob/main/skills/matlab-performance-optimizer/SKILL.md -a claude-code --skill matlab-performance-optimizerInstallation paths:
.claude/skills/matlab-performance-optimizer/# MATLAB Performance Optimizer
This skill provides comprehensive guidelines for optimizing MATLAB code performance. Apply vectorization techniques, memory optimization strategies, and profiling tools to make code faster and more efficient.
## 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:**
```matlab
% Slow approach
n = 1000000;
result = zeros(n, 1);
for i = 1:n
result(i) = sin(i) * cos(i);
end
```
**FAST - Vectorized:**
```matlab
% Fast approach
n = 1000000;
i = 1:n;
result = sin(i) .* cos(i);
```
### 2. Preallocate Arrays
**Always preallocate arrays before loops.**
**SLOW - Growing arrays:**
```matlab
% Very slow - array grows each iteration
result = [];
for i = 1:10000
result(end+1) = i^2;
end
```
**FAST - Preallocated:**
```matlab
% 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:**
```matlab
% Slow
sum_val = 0;
for i = 1:length(x)
sum_val = sum_val + x(i);
end
```
**FAST - Built-in function:**
```matlab
% Fast
sum_val = sum(x);
```
## Vectorization Techniques
### Element-wise Operations
Use `.*`, `./`, `.^` for element-wise operations:
```matlab
% 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:
```matlab
% Instead of this:
count = 0;
for i = 1:length(data)
if data(i) > threshold
count = count + 1;
fil