2016-01-25 35 views
2

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

什么我迄今所做的:

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

2)我创造的50种鱼类鱼类群随机x,y坐标和我绘制它们(群体坐标保存在一个数组中),

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 
+0

代码一直很受欢迎,因为这是编程问题的网站。请参阅[mcve] – Adriaan

+0

谢谢!我编辑了包含代码的帖子。我希望帮助 – Jason2000

+0

问题是什么? – excaza

回答

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步,然后由显示的伪动画鱼在移动。

这是有点你试图做什么?

+0

编辑它,所以它的工作! – Lui