单行道行车模拟(元胞自动机)——greatji1994

原创代码,转载请注明出处


function []=CellAuto2()

global num_cell max_velocity

num_cell = 100;

max_velocity = 5;

cell = zeros(2,num_cell);%ÿһÁÐÊÇÒ»¸öϸ°û£¬ÐзֱðÊÇλÖã¨0±íʾûÓгµ,1±íʾÓгµ£©£¬Ëٶȣ¬

cell_temp = cell;

 

for k = 1:1:1000

    if cell(1,1) == 0

        if rand(1,1) <= 0.5

            cell_temp(1,1) = 1;

            cell_temp(2,1) = fix(max_velocity*rand(1,1))+1;

        end

    elseif isequal(cell(1,2:(1+cell(2,1))),zeros(1,cell(2,1)))%µÚÒ»Á¾³µµÄºóÃ浥λʱ¼äËüÄܵ½´ïµÄµØ·½ÒªÃ»ÓгµÁ¾²ÅÄÜÒƶ¯

        cell_temp(1,1) = 0;

    end

    s = 2;

    while s <= num_cell;

        cell_temp = Calculate(cell,s,cell_temp);

        s = s + 1;

    end

    cell = cell_temp

    count = 0;

    for ss = 1:1:num_cell

        axis([0 4 1 num_cell]);

        if cell(1,ss) == 1

            if(count == 1)

                hold on;

            end

            plot(2,ss,'*');

            count = count + 1;

        end

    end

    hold off;

    pause(0.1);

end

end

 

function c = Calculate(cell,s,cell_temp)

global num_cell max_velocity

    c = cell_temp;

    if s <= max_velocity%¶ÔÓÚºóÃæµÄ³µÁ¾ÊýÉÙÓÚ×î´óµ¥Î»Ê±¼äÒƶ¯¾àÀ루Ëٶȣ©µÄÇé¿ö

        k = s - 1;

        if cell(1,s) == 0

        while k >= 1

            if cell(1,k) == 1

                if cell(2,k) == s - k;

                    c(:,s) = cell(:,k);

                end

                break;

            end

            k = k - 1;

        end

        elseif isequal(cell(1,(s+1):(s+cell(2,s))),zeros(1,cell(2,s)))

            c(1,s) = 0;

        end

    end

    if cell(1,s) == 1 && s + cell(2,s) > num_cell

        k = s - 1;

        if cell(1,s) == 0

        while k >= s - max_velocity

            if cell(1,k) == 1

                if cell(2,k) == s - k;

                    c(:,s) = cell(:,k);

                end

                break;

            end

            k = k - 1;

        end

        elseif isequal(cell(1,(s+1):num_cell),zeros(1,num_cell-s))

            c(1,s) = 0;

        end

    end

    if s + cell(2,s) <= num_cell && s > max_velocity

        k = s - 1;

        if cell(1,s) == 0

        while k >= s - max_velocity

            if cell(1,k) == 1

                if cell(2,k) == s - k;

                    c(:,s) = cell(:,k);

                end

                break;

            end

            k = k - 1;

        end

        elseif isequal(cell(1,(s+1):(s+cell(2,s))),zeros(1,cell(2,s)))

            c(1,s) = 0;

        end

    end

end

                    


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值