Index out of bounds
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Star Strider
2015-6-1
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 个评论
Star Strider
2015-6-2
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);
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!