移动的汽车模拟火车

时间:2016-04-26 17:32:25

标签: matlab simulation

我们正在尝试使用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后,汽车阵列中的下一个车型移动等等,直到汽车阵列结束)

任何人都可以帮忙吗?

提前致谢

1 个答案:

答案 0 :(得分: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