Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Matlab Code-Problem with loop.

Subject: Matlab Code-Problem with loop.

From: Casi

Date: 3 Jun, 2011 21:40:19

Message: 1 of 2

So, I'm trying to run a random code that should randomize the results with a variable number of particles. As it stands, the code will keep running until the time runs out but will not stop when it goes above the allocated number of particles. I tried putting that in the while statement, but it doesn't seem to be working. The code is below:


function[]=mult(a0,b0,k,tf)

%%This function uses multiple particles in a
%%bistable system and a transition rate from state a to state b of k.

runs=a0+b0;

for i=1:runs
    
    t=0;
    a=a0;
    b=b0;
    rand('state', sum(100*clock));
    tt=[];
    aa=[];
    bb=[];

    while ((a+b)<=(a0+b0) && t<=tf)
        tt=[tt t];
        aa=[aa a];
        bb=[bb b];
        r=rand(1);

        if r>k
            anew=a+1;
            bnew=b-1;
        else
             anew=a-1;
             bnew=b+1;

        end
        a=anew;
        b=bnew;
        t=t+1;
    end
end


plot(tt,aa,'k','linewidth',2)
set(gca,'Fontname','Helvetica','Fontsize',16);
xlim([0,tf])
xlabel('Time','Fontsize',16)
ylabel('State','Fontsize',16)
set(gca,'Box','off');
title(['Gillespie algorithm with multiple particles and ', num2str(k*100),'% chance of switching'],'Fontsize',14)

print -depsc2 mult.eps

Subject: Matlab Code-Problem with loop.

From: Roger Stafford

Date: 4 Jun, 2011 00:14:05

Message: 2 of 2

"Casi " <beatlesschic@gmail.com> wrote in message <isbkc3$i9r$1@newscl01ah.mathworks.com>...
> So, I'm trying to run a random code that should randomize the results with a variable number of particles. As it stands, the code will keep running until the time runs out but will not stop when it goes above the allocated number of particles. I tried putting that in the while statement, but it doesn't seem to be working. The code is below:
> .........
> while ((a+b)<=(a0+b0) && t<=tf)
> .........
- - - - - - - - - - -
  I see nothing to stop the while loop except t>tf. The sum a+b will never change from a constant a0+b0. I see nothing that would detect if either a or b become negative, so the while loop could easily continue on with a negative number of particles in either a or b. Is that what you observed? If you want it to stop when either becomes negative, you should test for that.

Roger Stafford

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us