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

3 次查看(过去 30 天)
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 );

采纳的回答

Praveen Iyyappan Valsala
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 个评论
jacob Mitch
jacob Mitch 2019-11-9
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!

请先登录,再进行评论。

更多回答(0 个)

Community Treasure Hunt

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

Start Hunting!

Translated by