Index in position 1 is invalid. Array indices must be positive integers or logical values.

1 次查看(过去 30 天)
I want to solve problem using Runge-Kutta 4th method but my coding have error of "Index in position 1 is invalid. Array indices must be positive integers or logical values, Error in (line 25), k1=h*f(t(i),y(i));"
The coding is as below:
%Setup
clear all;
close all;
clc;
% Define input values
g = 9.81; % acceleration of gravity (m/s^2)
v = 20; % initial speed (m/s)
theta = 30 * pi/180; % angle (rad)
%Define step size
h = 0.1;
% Define initial condition
t(1)=0;
y(1)=0;
%Define the equation
f=@(t,y) y;
f=v*sin(theta)-g*t;
%RK 4th method
for i=1:24
k1=h*f(t(i),y(i));
k2=h*f(t(i)+h/2,y(i)+k1/2);
k3=h*f(t(i)+h,y(i)+k2);
k4=h*f(t(i)+h,y(i)+k3);
t(i+1) = t(i)+h;
y(i+1)=y(i)+1/6*(k1+2*k2+2*k3+k4);
end
%Plot graph as result
plot (t,y,':'), axis ([0 2.5 0 7]), grid

采纳的回答

Angelo Yeo
Angelo Yeo 2023-6-21
编辑:Angelo Yeo 2023-6-21
You have defined two different f's in line 15 and 16.
>> f=@(t,y) y; % line 15
>> f=v*sin(theta)-g*t; % line 16
Below is the changed code and result.
%Setup
clear;
close all;
clc;
% Define input values
g = 9.81; % acceleration of gravity (m/s^2)
v = 20; % initial speed (m/s)
theta = 30 * pi/180; % angle (rad)
%Define step size
h = 0.1;
% Define initial condition
t(1)=0;
y(1)=0;
%Define the equation
% f=@(t,y) y;
f=@(t,y) v*sin(theta)-g*t;
%RK 4th method
for i=1:24
k1=h*f(t(i),y(i));
k2=h*f(t(i)+h/2,y(i)+k1/2);
k3=h*f(t(i)+h,y(i)+k2);
k4=h*f(t(i)+h,y(i)+k3);
t(i+1) = t(i)+h;
y(i+1)=y(i)+1/6*(k1+2*k2+2*k3+k4);
end
%Plot graph as result
plot(t,y,':'), axis ([0 2.5 0 7]), grid

更多回答(2 个)

Mrinal Anand
Mrinal Anand 2023-6-21
The error is because you have indexed t and y without initializing them as arrays:
t(1)=0;
y(1)=0;
Your for loop required 25 values for t and y, so you should initialise them as arrays:
% Define initial condition
t = zeros(1,25);
y = zeros(1,25);
In addition, you have given two definitions for f. I am assuming you want to use the second equation, hence you should use '@' to define that as a function rather than the first one:
%Define the equation
f = @(t,y) v*sin(theta)-g*t;
Your code should run after these changes.

Kanishk Singhal
Kanishk Singhal 2023-6-21
You are having some confusion at line 22 and line 23,
f=@(t,y) y; % 22
f=v*sin(theta)-g*t; % 23
You are defing 'f' as a function at line 22 but over riding it at line 23, as a value.
Then you are using f as a function at line 25 but as it is overridden as value MATLAB is trying to access it as matrix as you have provided row and coloumn in form of t(1) and y(1) and thus throwing the error.
I think what you were trying to do was,
f=@(t,vy) vy*sin(theta)-g*t;
You might also want to check your equations in the for loop and the axis ranges in last line.

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by