2

我有一个项目,要在 matlab 上创建一个非常基本的 PSO(鱼群)。

到目前为止我所做的:

1)我已经设置了轴的尺寸,

2) 我用随机的 x,y 坐标创建了一个由 50 条鱼组成的鱼群并绘制它们(群坐标保存在一个数组中),

3)我点击图上的某个地方,我得到了代表鲨鱼的点击坐标。

4)我计算最远的鱼的最佳x,y位置。

现在,我必须强迫其余的鱼靠近最佳位置的鱼。

这是代码;

Dx=100;
Dy=100;
axis([0 Dx 0 Dy]);
N=50;
K=4;
d=min(Dx,Dy)/K;
click=ginput(1);
fish=zeros(50,4);
i=1;
while i<=N
    x= rand * Dx;
    y= rand * Dy;
    if d>=sqrt((click(1)-x)^2+(click(2)-y)^2)
         fish(i,1)=x;
         fish(i,2)=y;
         hold on;
         plot(x,y,'o'); % fishes
         i=i+1;
    end;
end;

click1=ginput(1);
bestposition=1;
i=1;
while i<=N
    position=sqrt((click1(1)-fish(i,1))^2+(click1(2)-fish(i,2))^2);
    if i==1
        max=position;
    else
        if max<position
            max=position;
            bestposition=i;
        end
    end
    i=i+1;
end

hold on;
plot(click1(1), click1(2), 'r*'); %shark
4

1 回答 1

0

我采用了您的代码,更改了后半部分,并添加了一些代码:

Dx=100;
Dy=100;
axis([0 Dx 0 Dy]);
N=50;
K=4;
d=min(Dx,Dy)/K;
click=ginput(1);
fish=zeros(50,4);
i=1;
while i<=N
    x= rand * Dx;
    y= rand * Dy;
    if d>=sqrt((click(1)-x)^2+(click(2)-y)^2)
         fish(i,1)=x;
         fish(i,2)=y;
         hold on;
         plot(x,y,'o'); % fishes
         i=i+1;
    end;
end;

click1=ginput(1);
distances = pdist2(click1, fish(:,1:2));
[bestPosition, bestFish] = max(distances);

fish(:,3) = fish(bestFish,1) - fish(:,1);
fish(:,4) = fish(bestFish,2) - fish(:,2);
% I'm assuming this is what the other columns are for
fish(:,3:4) = normr(fish(:,3:4));
% The best fish is going away from the shark
fish(bestFish,3:4) = normr(fish(bestFish,1:2) - click1);

% Let's say the smarm moves 1 +/- .5 each move, and not exactly towards
for i0 = 1:100
    % Towards the best fish
    pause(0.05);
    fish(:,1:2) = fish(:,1:2) + (fish(:,3:4).*(rand(size(fish(:,3:4))) + 1)/10);

    fish(:,3) = fish(bestFish,1) - fish(:,1);
    fish(:,4) = fish(bestFish,2) - fish(:,2);
    % I'm assuming this is what the other columns are for
    fish(:,3:4) = normr(fish(:,3:4));
    fish(bestFish,3:4) = normr(fish(bestFish,1:2) - click1);

    cla;
    plot(fish(:,1), fish(:,2), 'o')
    plot(fish(bestFish,1), fish(bestFish,2), 'rO');
    plot(click1(1), click1(2), 'kO');
end

我已经完成了您的步骤 1-4,然后制作了一个显示鱼移动的伪动画。

这有点像你想要做的吗?

于 2016-01-25T22:02:51.623 回答