Modeling on MATLAB

enter image description here

I need to make a simulation of ants moving between their house (black box) and food (yellow box). These triple colored boxes are ants. The code I wrote to draw the picture shown is as follows:

% background background() % making ants handle = zeros(10,3) handle = makingAnts(10) ; % moving ants movingAnts(hand) 

Functional Background:

  function background() figure hold on axis equal axis([0 100 0 100]) pos = rand(1,2).*75 rectangle('position',[0 0 10 10],'facecolor','k') rectangle('position',[pos 25 25],'facecolor','y') end 

function making ants:

  function [h] = makingAnts(n) h = zeros(10,3) dia = [2 2] for i = 1:n pos = rand(1,2).* 95 ; h(i,1) = rectangle('position',[pos dia],'facecolor',[0.2 0.6 1]) g1 = get(h(i,1),'position') h(i,2) = rectangle('position',[(g1(1)+2) (g1(2)+2) 2 2],'facecolor',[0.4 1 0.6]) h(i,3) = rectangle('position',[(g1(1)+4) (g1(2)+4) 2 2],'facecolor',[1 0.8 1]) end end 

Now I need to move the ants. Although I wrote the code, but it does not work. I need help getting the ants to move.

Code I wrote:

  function movingAnts(h) % moving 1 ant pos = get(h(1),'position') m = pos(1) n = pos(2) for i = 1:50 set(h(1),'position',[(m+0.2) (n+0.2) 2 2]) pause(0.05) end end 
+5
source share
3 answers
 figure axis([0 100 0 100]) rectangle('position',[0 0 5 5],'facecolor','k') rectangle('position',[95 95 100 100],'facecolor','y') n = 5; x = zeros(1,n); y = zeros(1,n); c = ones(1,n); while 1 for i = 1 : n h1(i) = rectangle('position',[x(i) y(i) 2 2],'facecolor',[0.2 0.6 1]); g1 = get(h1(i),'position'); h2(i) = rectangle('position',[(g1(1)+2) (g1(2)+2) 2 2],'facecolor',[0.4 1 0.6]); h3(i) = rectangle('position',[(g1(1)+4) (g1(2)+4) 2 2],'facecolor',[1 0.8 1]); x(i) = x(i) + c(i) * randi(4,1); y(i) = y(i) + c(i) * randi(4,1); if x(i) > 100 || y(i) > 100 c(i) = -1 * c(i); x(i) = 100; y(i) = 100; end if y(i) < 0 || x(i) < 0 c(i) = -1 * c(i); x(i) = 0; y(i) = 0; end end pause(.1) delete(h1,h2,h3); end 

enter image description here

+4
source

As @ franz1 noted, the problem is that the variables m and n are out of loop and therefore are not updated. To continue his answer, here is a possible movingAnts.m function:

 function movingAnts(h) h = reshape(h,numel(h),[]); for i = 1:50 pos = get(h,'position'); % move all ants pos = cellfun(@(x) x+[1,1,0,0], pos, 'UniformOutput', false); set(h,{'position'},pos); drawnow update %display updates pause(0.1); end end 

enter image description here

In addition, you should change the definition of h in makingAnts.m to:

 h = zeros(n,3); 
+4
source
 for i = 1:50 set(h(1),'position',[(m+0.2) (n+0.2) 2 2]) pause(0.05) end 

Since m, n are constants, here you put ant at the same position on each iteration.

+2
source

Source: https://habr.com/ru/post/1206943/


All Articles