Index out of bounds

3 visualizaciones (últimos 30 días)
Tadgh Cullen
Tadgh Cullen el 1 de Jun. de 2015
Comentada: Star Strider el 2 de Jun. de 2015
I'm relatively new to MATLAB and my code is throwing the error "Attempted to access v(2,1); index out of bounds because numel(v)=1. Error in ForcedVortex (line 82) dvdx=(v(ii+1,jj)-v(ii,jj))/(x(ii,jj)-x(ii,jj)); "
This is the code, its to calculate the vorticity at each point and visualise a forced vortex.I thought it was a boundary error problem so replaced introduced a second iteration ii and jj but that didn't solve the problem. Would appreciate any help
%%Read in and set data
dx=1;
dy=1;
k=1;
f=1 %this is used in the angular momentum omega equation. Double check
omega=2*pi*f;
A1=9;
B1=10;
for i=1:A1
for j=1:A1
for ii=1:B1-1
for jj=1:B1-1
x(i,j)=(-5)+(i.*dx);
y(i,j)=(-5)+(j.*dy);
r=sqrt((x(i,j)^2)+(y(i,j)^2));
utheta=omega*r;
ur=0;
sintheta=(y(i,j)/r)
costheta=(x(i,j)/r)
u(i,j)=(-utheta).*(sintheta);
v(i,j)=(utheta).*(costheta);
dvdx=(v(ii+1,jj)-v(ii,jj))/(x(ii+1,jj)-x(ii,jj));
dudy=(u(ii,jj+1)-u(ii,jj))/(y(ii,jj+1)-y(ii,jj));
VorticityPoint=(dudy-dvdx)*k;
Vorticity(i,j)=VorticityPoint
end
end
end
end
imagesc(Vorticity),colorbar

Respuesta aceptada

Star Strider
Star Strider el 1 de Jun. de 2015
The error is arising because you’re calling v(ii+1,jj) when you have only defined v(i,j) and ‘i’ and ‘j’ are both 1 in the outer loops. (The inner loops will of course increment faster than the outer loops.)
You can likely eliminate that error by preallocating ‘u’ and ‘v’ before the loop, and after you have assigned ‘A1’ and ‘B1’. For instance:
v = zeros(A1);
u = zeros(A1);
That will initialise them both to (A1xA1) matrices of zeros.
  2 comentarios
Tadgh Cullen
Tadgh Cullen el 2 de Jun. de 2015
I'm still getting the same error. I introduced ii and jj because otherwise the vorticity equation was attempting to access u(1,10) so I decided to accept that there would be a boundary error but that it was acceptable.
I wonder if there is a way of getting them to all iterate at the same time so when i=2 ii=2? I think that would solve the problem?
Thanks
Star Strider
Star Strider el 2 de Jun. de 2015
Preallocate all your matrices as size A1+1 and it runs. However, there are still problems because I doubt the result you get is the one you want. I don’t understand what you’re doing, so I can’t help you troubleshoot the calculation problems.
Add these lines just before the first for statement:
u = zeros(A1+1);
v = zeros(A1+1);
x = zeros(A1+1);
y = zeros(A1+1);

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by