
I am trying to plot the decision boundary for extreme learning machine but I am getting the error "To RESHAPE the number of elements must not change"
3 views (last 30 days)
Show older comments
Can you please tell where i am doing the mistake in the below code.
data = load('example1.txt');
% Split the data into training and testing sets
train_data = data(1:30,1:2); % Features
train_label = data(1:30,3); % Labels
test_data = data(31:51,1:2);
test_label = data(31:51,3);
% Train ELM model
elm = elm_train([train_data train_label] , 1, 7, 'sigmoid')
% Create a grid of points covering the space of the input data
minX1 = min(data(:,1));
maxX1 = max(data(:,1));
minX2 = min(data(:,2));
maxX2 = max(data(:,2));
[x1Grid, x2Grid] = meshgrid(minX1:0.1:maxX1, minX2:0.1:maxX2);
% Predict the output for the grid of points
yGrid = elm_predict([test_data test_label]);
hold on;
scatter(test_data( test_label==0,1), test_data(test_label==0,2), 'b', 'o');
scatter(test_data(test_label==1,1), test_data(test_label==1,2), 'r', 'x');
y1=reshape(yGrid, size(x1Grid))
% Plot the decision boundary
contour(x1Grid, x2Grid, y1, [0.5, 0.5],'linewidth',1);
0 Comments
Answers (1)
Raag
on 2 May 2025
Hi uma,
As per my understanding, the error you are encountering is occurring because of a mismatch between the number of elements in the array you are trying to reshape “(yGrid)” and the size of the mesh grid “(x1Grid)” you are using for plotting the decision boundary.
The root cause is in your code, you are generating a mesh grid using the following lines:
[x1Grid, x2Grid] = meshgrid(minX1:0.1:maxX1, minX2:0.1:maxX2);
This mesh grid contains many points (depending on your data range and step size). However, when you make predictions for plotting the decision boundary, you are using:
yGrid = elm_predict([test_data test_label]);
Here, predictions are being made only on your test data (which has 21 points), not on the full set of grid points generated above. When you subsequently attempt to reshape ‘yGrid’ to the size of ‘x1Grid’, MATLAB throws an error because the number of elements does not match.
To resolve this, you should make predictions on the mesh grid points, not just on your test data. This ensures that the number of predictions matches the number of grid points, and the reshape operation will succeed:
[x1Grid, x2Grid] = meshgrid(minX1:0.1:maxX1, minX2:0.1:maxX2);
gridPoints = [x1Grid(:), x2Grid(:)]; % Each row is a point on the grid
yGrid = elm_predict(elm, gridPoints); % Predict on all grid points
y1 = reshape(yGrid, size(x1Grid)); % Now reshape will work
contour(x1Grid, x2Grid, y1, [0.5, 0.5], 'linewidth', 1); % Plot decision boundary
Output using a custom elm function:

For a better understanding of the above solution, refer to the following MATLAB documentations:
0 Comments
See Also
Categories
Find more on Line Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!