I use the PSO optimization algorithm and I get the error Unable to perform assignment because the size of the left side is 10-by-1 and the size of the right side is 1-by-3.

2 views (last 30 days)
This is how I wrote the code I used for the Particle swarm optimization (PSO) function:
function [best_mdl] = myELMtrain_PSO(data, dtrain, Nhid_min, Nhid_max)
actfunc = ["sigmoid", "relu", "leaky_relu", "tanh"];
% Initialize the PSO particles
p = 10;
particles = rand(p, 2);
particles(:, 1) = Nhid_min + (Nhid_max - Nhid_min) * particles(:, 1);
particles(:, 2) = actfunc(randperm(3));
% Evaluate the fitness of each particle
for i = 1:p
fitness(i) = myELMtrain(data, dtrain, particles(i, 1), particles(i, 2));
end
% Update the particles
for i = 1:p
for j = 1:p
if fitness(i) < fitness(j)
particles(j, :) = particles(i, {});
end
end
end
% Find the best particle
best_particle = particles(find(fitness == min(fitness)), :);
% Set the number of neurons and activation function to the best particle
Nhid = best_particle(1);
actfunc = best_particle(2);
best_mdl = myELMtrain(data, dtrain, Nhid, actfunc);
end
When I run the main code and call the function, I get the following error. Please help if possible. Thank you.
Unable to perform assignment because the size of the left side is 10-by-1 and the size of the right side is 1-by-3.
Error in myELMtrain_PSO (line 9)
particles(:, 2) = actfunc(randperm(3));
Error in pso_elm_classifier (line 19)
mdl{i} = myELMtrain_PSO(data, label, 10, 100);

Accepted Answer

Torsten
Torsten on 4 Jul 2023
Edited: Torsten on 4 Jul 2023
The reason for the error message is obvious. You can't save a 1x3 array (actfunc(randperm(3))) in a 10x1 array (particles(:, 2)). Further, the array classes differ: while "actfun" is a string array, "particles" is an array of doubles.

More Answers (0)

Products


Release

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!