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

New to MATLAB?

Help with "While" loop, not sure what I'm doing

Asked by Chris Parry

Chris Parry

on 16 Aug 2012
Accepted Answer by Jan Simon

Jan Simon

I have started learning to use Matlab, I have a program that a colleague of mine has written for processing my data and I can't figure out why some of the script is not working. In the following loop, the first equation (RHlsun) uses the original value of glsuni istead of the new value from the loop. I hope this makes sense. What am I doing wrong?

counter  = 0;
glsuni = 0.5;
glsun = 0.0;
converge1 = abs(glsuni - glsun);
while converge1>0.0005;
      RHlsun = 1 - (1 - (RH / 100)) .* (((2 * glsuni * ((fgreen * fdry) / fstomata)) .* gvl .* (gbc ./ LAIsun)) ./ ((2 * glsuni .* ((fgreen * fdry) / fstomata)) .* ((2 * glsuni .* ((fgreen * fdry) / fstomata)) .* gvl + (2 * glsuni .* ((fgreen * fdry) / fstomata)) .* (gbc ./ LAIsun) + gvl .* (gbc ./ LAIsun))));
      sRHlsun = (sqrt((RHlsun.^2) + (RHlmin^2))) ./ (sqrt(1 + (RHlmin^2)));
      CO2lsun = CO2i - (CO2i - CO2a) * (((2 * 0.625 * glsuni * ((fgreen * fdry) / fstomata)) .* gcl .* (gbc ./ LAIsun)) ./ ((2 * 0.625 * glsuni * ((fgreen * fdry) / fstomata)) .* ((2 * 0.625 * glsuni .* ((fgreen * fdry) / fstomata)) .* gcl + (2 * 0.625 * glsuni * ((fgreen * fdry) / fstomata)) .* (gbc ./ LAIsun) + gcl .* (gbc ./ LAIsun))));
      glsun = mBWB .* ((Ansun .* sRHlsun) ./ CO2lsun) + bBWB;
      counter = counter + 1;
      converge1 = abs(glsuni - glsun);
      glsuni = glsun;
       if counter > 30;
           break;
       end;
  end;

2 Comments

Nirmal

Nirmal

on 16 Aug 2012

What is the problem that you are having?

Tom

Tom

on 16 Aug 2012

That equation is processed before the counter=counter+1 line, so maybe move the counter to the top of the loop?

Chris Parry

Chris Parry

Tags

Products

No products are associated with this question.

1 Answer

Answer by Jan Simon

Jan Simon

on 18 Aug 2012
Edited by Jan Simon

Jan Simon

on 18 Aug 2012
Accepted answer

Start with a simplification of the code:

counter  = 0;
glsuni   = 0.5;
glsun    = 0.0;
converge = abs(glsuni - glsun);
c1 = (fgreen * fdry) / fstomata;
c4 = gbc ./ LAIsun;
while converge > 0.0005 || counter > 30
   c2 = 2 * glsuni * c1;
   c3 = c2 * 0.625;
     RHlsun   = 1 - (1 - (RH / 100)) ./ (c2 ./ c4 + c2 ./ gvl + 1);
     sRHlsun  = sqrt(RHlsun .^ 2 + RHlmin ^ 2) ./ sqrt(1 + RHlmin ^ 2);
     CO2lsun  = CO2i - (CO2i - CO2a) ./ (c3 ./ c4 + c3 ./ gcl + 1);
     glsun    = mBWB .* Ansun .* sRHlsun ./ CO2lsun + bBWB;
     converge = abs(glsuni - glsun);
     glsuni   = glsun;
     counter = counter + 1;
  end

Perhaps this allows you to see the problem by your own.

0 Comments

Jan Simon

Jan Simon

Contact us