index out of bounds because size(eta)=[1,2]

3 views (last 30 days)
Attempted to access eta(1,1000); index out of bounds because size(eta)=[1,2].
Error in surface (line 30)
eta(j,N)=eta(j,N)+eta(j,i);
Why do i get this error? Can anybody help me to understand?
clc
close all
N=1000; %number of regular wave components
d=0.4; %depth
A=0.15; %Hs
B=1.6; %Tp
f(1)=0.1; %starting frequency
ff=10;
deltaf=(ff-f(1))/(N-1);
f=f(1):deltaf:ff;
deltat=0.05; %time interval
t=0:deltat:1400; %time series
duration=length(t);
e=2*pi*rand(1,N); %phase angle
for i=1:N;
T(i)=1/f(i); %period
L(i)=dispersion(T(i),d); %wavelength
k(i)=2*pi/L(i);
n(i)=0.5*(1+((2*k(i)*d)/sinh(2*k(i)*d)));
a(i)=(2*deltaf*(0.205*(A^2)*(B^-4)*(f(i)^-5)*exp(-0.75*(B*f(i))^-4)))^0.5;
end
m=zeros(1,duration);
j=1;
for t=0:deltat:1400;
for i=1:N;
eta(j,i)=a(i)*cos(2*pi*f(i)*t+e(i));
eta(j,N)=eta(j,N)+eta(j,i);
end
end
plot(eta(:,1),eta(:,N))
xlabel('Time (sec)')
ylabel('Surface Elevation,\eta (m)')

Accepted Answer

Geoff Hayes
Geoff Hayes on 7 Dec 2018
dj - on the first iteration of your inner for loop
j=1;
for t=0:deltat:1400;
for i=1:N;
eta(j,i)=a(i)*cos(2*pi*f(i)*t+e(i));
eta(j,N)=eta(j,N)+eta(j,i);
end
end
since you never pre-size (or pre-allocate memory) to eta then it is a 1x1 scalar when you do the first assignment for eta(j,i). On the next line you try to update and access the 1000th (N) element of this scalar...and since it doesn't exist, the access is probably what is throwing the error. You probably want to pre-size the array before entering the outer for loop
eta = zeros(1,N);
While that should fix the error, is it really what you want to do? Why is j never incremented? The fact that it isn't seems to conflict with your call to plot
plot(eta(:,1),eta(:,N))
In the above, you are assuming that eta is a column array but you are initializing it as if it were a row array. I suspect also that the above call to plot is not really what you want unless you are assuming that eta is an axN matrix and so you are plotting with the first and last columns of eta.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!