how to call functions properly: Index in position 1 is invalid. Array indices must be positive integers or logical values.

1 visualización (últimos 30 días)
I'm trying to work with multiple functions but I keep getting this error, its for the runge kutta method solving rossler equations.
% The code Im trying to run
clear
u0=[0.116365;0.376326;0.946238];
[ t, y ] = runge ( 'ross', [ 0.0, 200.0 ], u0, 15000 );
plot3(y(1,:),y(2,:),y(3,:))
Which calls my runge function
function [t,y]=runge(f,timespan,u0,N);
N=round(timespan(2)*10);
y=u0;
h=(timespan(2)-timespan(1))/N;
t=linspace(timespan(1),timespan(2),N+1);
for i=1:N
k1=f(t(i),y(:,i)); %here is where the error occurs
k2=f(t(i)+0.5*h,y(:,i)+0.5*h*k1);
k3=f(t(i)+0.5*h,y(:,i)+0.5*h*k2);
k4=f(t(i)+h,y(:,i)+h*k3);
y(:,i+1)=y(:,i)+h*((k1+k4)/6+(k2+k3)/3);
end
I also have ross as
function y0 = ross ( t, y )
y0 = [ (-1*(y(2))-y(3)); y(1)+(0.1*y(2)); 0.1+y(3)*(y(1)-10)];
Command window prints
Index in position 1 is invalid. Array indices must be positive integers or logical values.
Error in runge(line 10)
k1=f(t(i),y(:,i));
Error in untitled11 (line 3)
[ t, y ] = runge ( 'ross', [ 0.0, 200.0 ], u0, 15000 );

Respuesta aceptada

Praveen Iyyappan Valsala
Praveen Iyyappan Valsala el 9 de Nov. de 2019
In your runge function, f is a string not a function.
k1=eval(strcat(f,'(t(i),y(:,i));'));%f(t(i),y(:,i)); %here is where the error occurs
k2=eval(strcat(f,'(t(i)+0.5*h,y(:,i)+0.5*h*k1);'));%f(t(i)+0.5*h,y(:,i)+0.5*h*k1);
k3=eval(strcat(f,'(t(i)+0.5*h,y(:,i)+0.5*h*k2);'));%f(t(i)+0.5*h,y(:,i)+0.5*h*k2);
k4=eval(strcat(f,'(t(i)+h,y(:,i)+h*k3);'));%f(t(i)+h,y(:,i)+h*k3);
Alternatively, you can pass function handles
ross =@( t, y ) [ (-1*(y(2))-y(3)); y(1)+(0.1*y(2)); 0.1+y(3)*(y(1)-10)]; % your ross function
[ t, y ] = runge ( ross, [ 0.0, 200.0 ], u0, 15000 );
  1 comentario
jacob Mitch
jacob Mitch el 9 de Nov. de 2019
wow thank you so much I've deleted
function y0 = ross ( t, y )
y0 = [ (-1*(y(2))-y(3)); y(1)+(0.1*y(2)); 0.1+y(3)*(y(1)-10)];
and am running it as so as you've suggested and it seems to be working well!
clear
u0=[0.116365;0.376326;0.946238];
ross =@( t, y ) [ (-1*(y(2))-y(3)); y(1)+(0.1*y(2)); 0.1+y(3)*(y(1)-10)]; % your ross function
[ t, y ] = runge ( ross, [ 0.0, 200.0 ], u0, 15000 );
plot3(y(1,:),y(2,:),y(3,:))
Just double checking but thank you!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Nonlinear Dynamics en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by