Link to home
Start Free TrialLog in
Avatar of Cluskitt
CluskittFlag for Portugal

asked on

Best way to split two dimensional arrays into smaller ones (VB.Net)

Let's imagine I have an array MyArr1(5, 5). Type isn't important. What would be the best way to split this array into a smaller one? For example, I want MyArr2(3, 3) to be the same as MyArr1(1 to 3, 2 to 4).

If it were a one dimensional array, I could just do:
Array.Copy(MyArr1,1,MyArr2,0,3)
But I don't see how that could work for multi-dimension arrays.

The only way I can think of it to create a loop and populate on a one by one basis. Don't know if there's a better way to do this, but for larger dimension arrays it seems like a very inefficient method.

Any ideas on the best way to tackle this?
Avatar of TommySzalapski
TommySzalapski
Flag of United States of America image

The way arrays are stored in memory make it so Array.Copy is quite efficient for 1D arrays. It also makes it so there is no super-efficient way to copy pieces of 2D arrays.
If you are copying the entire array, then it can be efficient, but with chunks like that, you're not hurting anything using loops.

Now, don't do them one-by-one with a nested loop though. Make one loop and use Array.Copy to copy the 1D arrays. (Think of a 2D array as a 1D array of 1D arrays and it should make sense).

Forgive the syntax (I'm not a VB guy) but something like this
For i = 1 to ArrayHeight
  Array.Copy(MyArr1(i),1,MyArr2(2+i),0,3) 'Trying to offset so 1,1 starts at 3,0.
Next
Avatar of Cluskitt

ASKER

Actually, MyArr2 should start at 0. I think what you're suggesting would be more like:
For i = 1 to 3
  Array.Copy(MyArr1(i),2,MyArr2(i-1),0,3) 'Trying to offset so 1,1 starts at 3,0.
Next

This would loop "columns" 2 to 4 and "rows" 1 to 3 of MyArr1 and place them on MyArr2(0 to 2, 0 to 2)

I suppose, if I had a 3 dimensional array, I would still have to do a nested loop. This would just save one loop.

I was thinking more on the terms of some sort of Redim, actually. If I wanted to simply cut the last rows/cols, I would redim to a smaller number. I wonder if there's a way to do that for the first rows/cols... maybe with reverse? I'm really not sure how reverse works on multi-dimensional arrays, if at all.
ASKER CERTIFIED SOLUTION
Avatar of TommySzalapski
TommySzalapski
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks.