Fixing "Index Exceeds Matrix Dimensions" in MATLAB Neural Networks
This error occurs in MATLAB Neural Network Toolbox (Deep Learning Toolbox) when data orientations, sample counts, or target formats do not match the dimensions expected by the network.
1. Cause #1: Samples vs. Features Orientation (Most Common)
MATLAB standard neural networks (fitnet, patternnet, feedforwardnet) require features in rows and samples in columns.
Wrong: Passing
X as [N_samples x N_features] and Y as [N_samples x N_outputs].Fix: Transpose both inputs and targets before training.
% Suppose X has 500 samples and 4 features (500x4)
% Suppose Y has 500 target values (500x1)
% Transpose to [Features x Samples]
X_train = X'; % Now 4 x 500
Y_train = Y'; % Now 1 x 500
net = fitnet(10);
net = train(net, X_train, Y_train);
2. Cause #2: Incorrect Indexing of Training Record (tr)
When you extract partition indices (tr.trainInd, tr.valInd, tr.testInd), remember that samples are stored in columns.
% Correct: Index columns
train_X = X_train(:, tr.trainInd);
train_Y = Y_train(:, tr.trainInd);
% Wrong: Indexing rows causes "Index exceeds matrix dimensions"
% train_X = X_train(tr.trainInd, :);
3. Cause #3: Target Label Format in Classification (patternnet)
For multi-class classification with \(C\) classes, patternnet requires a one-hot encoded matrix of size [C x N_samples], not a single vector of integer class labels (1, 2, 3).
% If your labels are class indices: labels = [1; 2; 3; 1; 2; ...]; (1 x N)
% Convert to one-hot binary vectors using ind2vec:
Y_onehot = full(ind2vec(labels)); % Produces [NumClasses x NumSamples]
net = patternnet(10);
net = train(net, X_train, Y_onehot);
4. Cause #4: Sample Count Mismatch Between X and Y
The number of columns in X and Y must be identical.
% Check dimensions before training
fprintf('X size: %d features x %d samples\n', size(X_train, 1), size(X_train, 2));
fprintf('Y size: %d outputs x %d samples\n', size(Y_train, 1), size(Y_train, 2));
if size(X_train, 2) ~= size(Y_train, 2)
error('Number of samples in X and Y must match.');
end
Quick Dimension Reference Table
| Object | Expected Shape | Description |
|---|---|---|
Input Matrix X | [NumFeatures x NumSamples] | Each column is one data point. |
Regression Target Y | [NumOutputs x NumSamples] | Each column is the target output. |
Classification Target Y | [NumClasses x NumSamples] | One-hot binary encoding (0s and 1s). |
Output Predictions Y_hat | [NumOutputs x NumSamples] | Network evaluation output. |
Need a Custom Version or Complete Simulation for This Problem?
Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.
Explore similar technical troubleshooting questions and verified MATLAB solutions: