2

I am trying to 'expand' an array (generate a new array with proportionally more elements in all dimensions). I have an array with known numbers (let's call it X) and I want to make it j times bigger (in each dimension).

So far I generated a new array of zeros with more elements, then I used broadcasting to insert the original numbers in the new array (at fixed intervals).

Finally, I used linspace to fill the gaps, but this part is actually not directly relevant to the question.

The code I used (for n=3) is:

import numpy as np
new_shape = (np.array(X.shape) - 1 ) * ratio + 1
new_array = np.zeros(shape=new_shape)
new_array[::ratio,::ratio,::ratio] = X

My problem is that this is not general, I would have to modify the third line based on ndim. Is there a way to use such broadcasting for any number of dimensions in my array?

Edit: to be more precise, the third line would have to be:

new_array[::ratio,::ratio] = X

if ndim=2 or

new_array[::ratio,::ratio,::ratio,::ratio] = X

if ndim=4

etc. etc. I want to avoid having to write code for each case of ndim

p.s. If there is a better tool to do the entire process (such as 'inner-padding' that I am not aware of, I will be happy to learn about it).

Thank you

3 Answers 3

3

array = array[..., np.newaxis] will add another dimension

This article might help

Sign up to request clarification or add additional context in comments.

Comments

2

You can use slice notation -

slicer = tuple(slice(None,None,ratio) for i in range(X.ndim))
new_array[slicer] = X

Comments

2

Build the slicing tuple manually. ::ratio is equivalent to slice(None, None, ratio):

new_array[(slice(None, None, ratio),)*new_array.ndim] = ...

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.