Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Copying one row of a 2D array to a 1-dimensional array.

Status
Not open for further replies.

AndrewMozley

Programmer
Oct 15, 2005
621
GB
I have a 2-dimensional of 3 columns by 4 rows. So :

ArrayA = {{x11,x12,x13},{x21,x22,x23},{x31,x32,x33},{x41,x42,x43}}
That is : ArrayA[1,3] = x13, ArrayA[3,2] = x32 . . . .&c

I want to copy one row (for example the 2nd row) of this array to a one dimensional array, ArrayB, so that ArrayB[1] = x21, ArrayB[2] = x22, ArrayB[3] = x23. How do I do this please?

Thanks. Andrew
 
1. Dimension a destination array 1-D
2. ACOPY(sourcearrayname,destinationarrayname,firstsourceelement,numberofelements,firstdestinationelement)

You need to know you can always address a 2-D array as a 1-D array, too. This means elements of the second row are either [2,1] to [2,3] or [4]-[6].
This may even be simple enough, compute (row-1)*columns+col and you have firstelement, in this case that is (2-1)*3+col = 3+col, as said: 4 to 6.
Number of array elements obviously is 3 and first element of the destination array of course 1, you want to copy into the start of the new arra.

Code:
DIMENSION ArrayB[3]
ACOPY(ArrayA,ArrayB,4,3,1)

Tested:
Code:
Dimension ArrayA[4,3]
ArrayA[2,1]=21
ArrayA[2,2]=22
ArrayA[2,3]=23

Dimension ArrayB[3]
Acopy(ArrayA,ArrayB,4,3,1)
? ArrayB[1]
? ArrayB[2]
? ArrayB[3]

If you would want to copy a column, that would be harder to do, but obviously you can always do a FOR loop to iterate the elements you want.

Bye, Olaf.


 
Thanks Olaf. That sets my mind at rest!

I think I was thinking of the old Clipper facilities, where you could refer to (all the elements) of a row of a 2D array and copy them into a 1-D array in (more or less) a single instruction.

But what you have explained is clear and effective. Thanks again.
 
Well, two lines is not much, is it? And ACOPY could also create the destination array, but you obviously have more control about its size, if you predefine it.

EDIT - To explain why control matters here:
At some points of the ACOPY help topic the help says the automatically created array will have the same size as the source array, which obviously would be wrong, if you want the destination array to be one dimensional. So control about the dimensioning of the destination array matters.

Bye, Olaf.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top