Search code examples
matlabrunge-kutta

How to increase number in range set till it gives a specific answer?


I've wrote a rungekutta code and there is a specific x range that it should calculate up to it. The problem is that the prof. wants a code that keeps on adding up by itself till it reaches the required answer.

I tried using the 'if' function but it only works once and no more (thus, even creating a mismatch in array lengths.

Code:

h=0.5;% step size
z=0.5;
x = 0:h:z;% the range of x
y = zeros(1,length(x)); 
y(1) = 50;% initial condition
F_xy = @(t,x) (37.5-3.5*x);%function



for i=1:(length(x)-1)% calculation loop
    k_1 = F_xy(x(i),y(i));
    k_2 = F_xy(x(i)+h,y(i)+h*k_1);

    y(i+1) = y(i) + (h/2)*(k_1+k_2);% main equation
    if y(i+1)>11
        x=0:h:z+1;

    end

end



disp (y(i+1))

Error of arrays length (shows that if function only works once)

   41.4063

 Error using plot
Vectors must be the same length.

Error in code6rungekutta2ndorder (line 30)
plot(x,y), grid on

it should keep on increasing by +1 in the 'z' variable till the answer of y(i+1) is less than 11. (correct z should be 9.5)


Solution

  • As @medicine_man suggested, you need a while loop:

    h=0.5;% step size
    z=0.5;
    x = 0;
    y = 50;% initial condition
    F_xy = @(t,x) (37.5-3.5*x);%function
    
    
    m = 0;
    while y(m+1) > 11
        m = m+1;
        x = x+h;
        k_1 = F_xy(x,y(m));
        k_2 = F_xy(x+h,y(m)+h*k_1);
    
        y(m+1) = y(m) + (h/2)*(k_1+k_2);% main equation
    
    end
    
    figure;
    plot(0:h:x, y);
    

    Your terminate condition, which is y(m+1) > 11, is checked at the beginning of each iteration of the while loop. In the loop, you can increment the value of x and update your y array. The loop runs until the terminate condition is met.

    The result of the above code:

    enter image description here