2016-04-26 44 views
-1

我們試圖模擬用Matlab這裏動車的列車,我們寫的代碼:動車模擬

function []=moving_cars() 
    figure('units','normalized','outerposition',[0 0 1 1]) 
    x = linspace(0,30,10); 
    y2=0.6; 
    y3=0.2; 
    y4=-0.2; 
    axis([0,20,-0.4,1.5]) 
    ax = gca; 
    hold on 
    //%road 
    plot(x,y2*ones(size(x)), 'LineWidth', 1,'Color','black') 
    hold on 
    plot(x,y3*ones(size(x)),'--', 'LineWidth', 1,'Color','black') 
    hold on 
    plot(x,y4*ones(size(x)), 'LineWidth', 1,'Color','black') 
    hold off 
    axis off 
    title('(Moving cars Simulation)') 
    set(gcf,'color','w') 
    //%load image data 
    [imageData0, map, alpha] = imread('00.png', 'png'); 
    [imageData1, map, alpha] = imread('20.jpg', 'jpg'); 
    [imageData2, map, alpha] = imread('27.jpg', 'jpg'); 
    //%create Figure and Axes objects 
    f1 = figure(1); 
    a0 = axes('Parent', f1); 
    a1 = axes('Parent', f1); 
    a2 = axes('Parent', f1); 
    //%Add Image objects to axes 
    image(imageData0, 'Parent', a0); 
    image(imageData1, 'Parent', a1); 
    image(imageData2, 'Parent', a2); 
    //%Resize and move the Image objects 
    set(a0, 'Units', 'Pixel', 'Position', [-160 150 150 70],'Box','off','Visible','off'); 
    set(a1, 'Units', 'Pixel', 'Position', [-160 150 150 70],'Box','off','Visible','off'); 
    set(a2, 'Units', 'Pixel', 'Position', [-160 150 150 70],'Box','off','Visible','off'); 
    axis off 
    //%generate the train 
    Train= car_train() 
    //%moving the cars 
    check_type(Train,a0,a1,a2); 
end 
function [Cars]= car_train() 
    //%create random car train (10 cars between 1:2) 
    Cars = round((2-1).*rand(5,1) + 1); 
end 
function[]= check_type(Cars,a0,a1,a2,a3,a6) 
    for k = 1:length(Cars) 
     if(Cars(k)==1) 
      for i=1:2:1800 
       set(a1, 'Position', get(a0,'Position') + [i 0 0 0]); 
       drawnow 
      end 
     elseif(Cars(k)==2) 
      for i=1:2:1800 
       set(a2, 'Position', get(a0,'Position') + [i 0 0 0]); 
       drawnow 
      end 
     end 
    end 
end 

的問題是,我們需要汽車的火車要利用汽車在移動不是汽車(後汽車行駛200汽車陣列中的下一個汽車類型移動等等直到汽車陣列的末端)

任何一個幫助?

在此先感謝

回答

2

您需要交換這些for循環:

for k = 1:length(Cars) 
    if(Cars(k)==1) 
    for i=1:2:1800 
     ... 

因爲現在你要爲每一輛汽車,做的一舉一動。你需要這樣做,爲每個位置移動火車。

function[]= check_type(Cars,a0,a1,a2,a3,a6) 
    for i=1:2:1800 
     for k = 1:length(Cars) 
      if(Cars(k)==1) 
       set(a1, 'Position', get(a0,'Position') + [i 0 0 0]); 
       drawnow 
      elseif(Cars(k)==2) 
       set(a2, 'Position', get(a0,'Position') + [i 0 0 0]); 
       drawnow 
      end 
     end 
    end 
end 
+0

你能用代碼證明這一點麼 – user3332603

+0

@ user3332603當然,你去了。這是未經測試的。你需要爲自己做測試腿部工作。 –

+0

@ Ben根據汽車類型來移動汽車的if語句怎麼樣? – user3332603