how to call functions properly: Index in position 1 is invalid. Array indices must be positive integers or logical values.
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
jacob Mitch
am 9 Nov. 2019
Kommentiert: jacob Mitch
am 9 Nov. 2019
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 );
0 Kommentare
Akzeptierte Antwort
Praveen Iyyappan Valsala
am 9 Nov. 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 Kommentar
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Nonlinear Dynamics finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!