# index exceeds the number of array elements

4 views (last 30 days)
Mostafa Moradi on 29 Mar 2021
Commented: Cris LaPierre on 29 Mar 2021
I try to plot the deflection of a simply supported beam using rk4 with the following initial conditions
y(0)=0 and y (L)=0
L= length of beam
close all
clear all
clc
%constants
E=20*10^9;
w=0.05;
h=0.1;
I= w*h^3/12;
L=5;
q=1500*L;
% converting 2nd ODE into two 1st ODE
% y''=(-q/2.*(x.^2-L.*x))/EI
% let y'=d , y(0)=0;
% define function handles
%y=(x, d) <= y(1,:)=y y(2,:)=d
Y= @(x,y) [ ...
y(2);
(-q/2.*(x.^2-L.*x))/(E*I)];
%stepsize
Length=5;
h=0.0001;
n=Length/h;
% initial conditions
% at position x=0 and x=L, position is fixed and thus y(1,1)
x(1)=0;
y(1,1)=0;
y(1,n)=0;
%loop
for i= 1:n
%timeloop
x(i+1)= x(i)+h;
%rk loop
k1= Y(x(i) ,y(:,i) );
k2= Y(x(i)+0.5.*h,y(:,i)+0.5.*k1.*h);
k3= Y(x(i)+0.5.*h,y(:,i)+0.5.*k2.*h);
k4= Y(x(i)+ h,y(:,i)+ k3.*h);
y(:,i+1)= y(:,i)+h.*(k1+2*k2+2*k3+k4)/6;
end
figure
plot (x, y(1,:))
title('question6')
hold on
plot (x, y(2,:))
hold on
a1=plot (x, y(1,:)) ; M1="distance vs position";
a2=plot (x, y(2,:)) ; M2="distance vs deflection";
legend([a1, a2],[M1, M2])
hold off

Cris LaPierre on 29 Mar 2021
The error message is telling you the issue. Somewhere in your code, you are indexing an array using an index value greater than the length of the array.
A=1:5;
% This works
a=A(5)
a = 5
% This does not
b=A(8)
Index exceeds the number of array elements (5).
Cris LaPierre on 29 Mar 2021
I suspect the issue is with your implementation of the runge-kutta method. That is a different question than the one asked here. You could search this forum to find hundreds of answers on implementing it.

R2020b

### Community Treasure Hunt

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

Start Hunting!

Translated by