Why Does My Matlab Code Give an Out of Bounds Error?

  • Context: MATLAB 
  • Thread starter Thread starter MaxManus
  • Start date Start date
  • Tags Tags
    Bounds Matlab
Click For Summary
SUMMARY

The forum discussion addresses an "Out of Bounds" error encountered in MATLAB code related to array indexing. The user defined 3D arrays pu and pv with dimensions (nx, ny, N) and attempted to access an index that exceeds the defined size. The error was traced back to incorrectly using the loop variable i for both loops instead of using j for the second loop. The corrected loop structure is for i = 2:(nx-1); for j = 2:(ny-1);.

PREREQUISITES
  • Understanding of MATLAB array indexing
  • Familiarity with 3D arrays in MATLAB
  • Knowledge of nested loops in programming
  • Basic debugging techniques in MATLAB
NEXT STEPS
  • Review MATLAB documentation on array indexing
  • Learn about MATLAB's error handling and debugging tools
  • Explore best practices for nested loops in MATLAB
  • Study MATLAB's matrix manipulation functions
USEFUL FOR

MATLAB programmers, students learning numerical methods, and anyone troubleshooting array-related errors in MATLAB code.

MaxManus
Messages
268
Reaction score
1
Hey, I have defined
Code:
pu = zeros(nx,ny,N);
pv = zeros(nx,ny,N);
pu(:,ny,:) = 1;

and written the loop:
line 38-40
Code:
 for i = 2:(nx-1);
        for i = 2:(ny-1);
            ps(i,j) = p(i,j,n) - a1*(pu(i+1,j,n) - pu(i,j,n)) -a2*(pv(i,j+1,n) - pv(i,j,n));

and I get the error
? Attempted to access pv(2,11,1); index out of bounds because size(pv)=[10,10,10].

Error in ==> fluidmekanikk at 40
ps(i,j) = p(i,j,n) - a1*(pu(i+1,j,n) - pu(i,j,n)) -a2*(pv(i,j+1,n) - pv(i,j,n));

Could someone help me with the error?
 
Physics news on Phys.org
Well, obviously, you tried to access p(2,11,1) which does not exist.

Looking at the indexes, it was probably pv(i,j+1,n), since that goes highest int he middle term.

Now... what range does j iterate over?
 
Hurkyl said:
Well, obviously, you tried to access p(2,11,1) which does not exist.

Looking at the indexes, it was probably pv(i,j+1,n), since that goes highest int he middle term.

Now... what range does j iterate over?

Thanks for fast reply and solution.
The code
Code:
for i = 2:(nx-1);
        for i = 2:(ny-1);
was supposed to be
Code:
for i = 2:(nx-1);
        for j = 2:(ny-1);
and I had used the j as variable earlier.
 
Last edited:

Similar threads

Replies
1
Views
3K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
4K
  • · Replies 41 ·
2
Replies
41
Views
10K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
1
Views
5K
Replies
7
Views
3K