【发布时间】:2014-01-28 04:55:23
【问题描述】:
我是 matlab 新手,我需要一些有关 matlab 代码的帮助。我想进行粒子群优化,我想单击鼠标来定义空间中的一个点,其窗口大小为 [min1, max1] 和 [min2, max2]。然后初始化一个由 n = 10 个粒子组成的簇,并搜索用户最初设置的点。
我的代码是这样的:
clear all;
numofdims = 30;
numofparticles = 50;
c1 = 2;
c2 = 2;
numofiterations = 1000;
V = zeros(50, 30);
initialpop = V;
Vmin = zeros(30, 1);
Vmax = Vmin;
Xmax = ones(30, 1) * 100;
Xmin = -Xmax;
pbestfits = zeros(50, 1);
worsts = zeros(50, 1);
bests = zeros(50, 1);
meanfits = zeros(50, 1);
pbests = zeros(50, 30);
initialpop = Xmin + (Xmax - Xmin) .* rand(numofparticles, numofdims);
X = initialpop;
fitnesses = testfunc1(X);
[minfit, minfitidx] = min(fitnesses);
gbestfit = minfit;
gbest = X(minfitidx, :);
for i = 1:numofdims
Vmax(i) = 0.2 * (Xmax(i) - Xmin(i));
Vmin(i) = -Vmax(i);
end
for t = 1:1000
w = 0.9 - 0.7 * (t / numofiterations);
for i = 1:numofparticles
if(fitnesses(i) < pbestfits(i))
pbestfits(i) = fitnesses(i);
pbests(i, :) = X(i, :);
end
end
for i = 1:numofparticles
for j = 1:numofdims
V(i, j) = min(max((w * V(i, j) + rand * c1 * (pbests(i, j) - X(i, j))...
+ rand * c2 * (gbest(j) - X(i, j))), Vmin(j)), Vmax(j));
X(i, j) = min(max((X(i, j) + V(i, j)), Xmin(j)), Xmax(j));
end
end
fitnesses = testfunc1(X);
[minfit, minfitidx] = min(fitnesses);
if(minfit < gbestfit)
gbestfit = minfit;
gbest = X(minfitidx, :);
end
worsts(t) = max(fitnesses);
bests(t) = gbestfit;
meanfits(t) = mean(fitnesses);
end
【问题讨论】:
-
我在代码initialpop = Xmin + (Xmax - Xmin) .* rand(numofparticles, numofdims);
-
它说 Error using .* 矩阵尺寸必须一致。 PSo 中的错误(第 35 行)initialpop = Xmin + (Xmax - Xmin) .* rand(numofparticles, numofdims);
-
表示尺寸不一样。请检查两个矩阵维度。
-
非常感谢。我想再问一个问题,我怎样才能改变尺寸;
-
使用
rehsape。参考mathworks.com/help/matlab/ref/reshape.html
标签: matlab graph particle-swarm