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

조회 수: 1 (최근 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
Praveen Iyyappan Valsala 2019년 11월 9일
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개)

카테고리

Help CenterFile Exchange에서 Nonlinear Dynamics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by