Using the C Math Library | ![]() ![]() |
Extending Two-Dimensional Assignment to N Dimensions
Two-dimensional assignment extends naturally to N-dimensions; simply use more index arguments. Let A
be a 3-by-3-by-2 three-dimensional array (two 3-by-3 pages):
1 4 7 2 5 8 3 6 9
10 13 16 11 14 17 12 15 18
Then the MATLAB expression A(:,:,2) = eye(3)
changes page 2 to the 3-by-3 identity matrix; A(1,:,:) = ones(1,3,2)
changes row 1 on both pages to be all ones; A(2,2,2)
= 42
changes the element at the middle of page 2 (the number 14
) to the number 42
, and so on.
It is very simple to convert these MATLAB indexed assignment expressions into MATLAB C Math Library indexed assignment expressions.
mlfIndexAssign(&A, "(?,?,?)", mlfCreateColonIndex(), mlfCreateColonIndex(), mlfScalar(2), mlfEye(mlfScalar(3), NULL));
As a result of this operation the 3-by-3 array on page 2 of A
becomes:
1 0 0 0 1 0 0 0 1
A(1,:,:)
= ones(1, 3, 2)
becomes
mlfIndexAssign(&A, "(?,?,?)", mlfScalar(1), mlfCreateColonIndex(), mlfCreateColonIndex(), mlfOnes(mlfScalar(1), mlfScalar(3), mlfScalar(2), NULL));
As a result of this operation row 1 on both pages of A
becomes all ones.
1 1 1 2 5 8 3 6 9
1 1 1 11 14 17 12 15 18
Finally, A(2,2,2)= 42
becomes:
mlfIndexAssign(A, "(?,?,?)", mlfScalar(2), mlfScalar(2), mlfScalar(2), mlfScalar(42));
As a result of this operation the element at (2,2,2)
changes to the number 42
.
10 13 16 11 42 17 12 15 18
If the array A
had more than three dimensions, the index strings would have more than three ?
's in them, and they would be followed by more than three index values. All of the other types of indexing discussed in this chapter (assigning to entire rows and columns, etc.) work equally well on N-dimensional arrays.
![]() | Assigning to All Elements | Deleting Array Elements | ![]() |