5
$\begingroup$

I have an $n \times m \times p$ array, let's call it $r$.

I want to obtain an $n \times m \times p \times 5$ array (let's call it $q$) where $q$ is the same as $r$ except that every non-zero component now has a 3 in the new, fourth entry.

That is,

q[[;;,;;,;;,3]]

should return an array identical to r, and

q[[;;,;;,;;,1]],  q[[;;,;;,;;,2]], q[[;;,;;,;;,4]], q[[;;,;;,;;,5]]

should all return arrays with zeroes in all components.

This is obviously quite easy to achieve by acting directly on the array rules, but for larger arrays this becomes quite inefficient and it would be good to implement in a way which acts directly on the sparse arrays.

$\endgroup$

2 Answers 2

7
$\begingroup$

Another possibility is:

q = TensorProduct[r, {0, 0, 1, 0, 0}]
$\endgroup$
6
$\begingroup$

Is this what you're after?

ArrayPad[
  ArrayReshape[r, Append[Dimensions[r], 1]],
  Append[ConstantArray[{0, 0}, ArrayDepth[r]], {2, 2}]
]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.