how to create a matlab code for runge kutta 4th order using implicit function..here i hv tried but it is showing error in line 16 as In an assignment A(I) = B, the number of elements in B and I must be the same.

7 views (last 30 days)
function [ t,x] = Untitled2(h)
%UNTITLED2 Summarx of this function goes here
% Detailed etplanation goes here
t = 0:h:3;
u=t.^2;
x(1) = 0;
fx = @(t,x) 2*u;
for i=1:(length(t)-1)
k1 = fx(t(i),x(i));
k2 = fx(t(i)+0.5*h,x(i)+0.5*h*k1);
k3 = fx(t(i)+0.5*h,x(i)+0.5*h*k2);
k4 = fx(t(i)+h,x(i)+k3*h);
x(i+1) = x(i) + (1/6)*(k1+2*k2+2*k3+k4)*h;
end
end

Accepted Answer

A Jenkins
A Jenkins on 14 Mar 2014
Edited: A Jenkins on 14 Mar 2014
Your anonymous function is not properly defined. You have declared
fx = @(t,x) 2*u
which claims to be a function of t and x, yet, it is a function of u, which is an array that you already calculated.
Then when you call fx(t(i),...) it returns that same array every time, instead of the value of some function fx at some point t,x. Since your x(i+1) is expected to be a scaler, but it sees that whole array, it throws an error.
You should update your fx function to be a function of t and x.
  3 Comments
Walter Roberson
Walter Roberson on 15 Mar 2014
runge kutta methods are not applicable to functions defined as a finite set of points (e.g., as an array).
If the array defines coefficient for a fixed form of equation then construct the function handle from the coefficients and equation.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!