'Can I get a similar behavior with numpy broadcasting to the following array assignment in matlab

Given array of ones, size 5, I'm trying to assign it with indices including those larger than 5 (assigned array). the following is Matlab behavior, is there an equivalent behavior in python ?

a = ones(5,1)

a =
     1
     1
     1
     1
     1

a([2,10,7]) = [2,3,5]

a =
     1
     2
     1
     1
     1
     0
     5
     0
     0
     3


Solution 1:[1]

To my knowledge it is not possible to use anything close to the matlab syntax with numpy. You either have to allocate the right size from the start, or append a new array/list to the previous one. Here are the two ideas that come to mind:

A: Right size from the start

This is the method I would prefer since it uses less dynamical allocation and thus, is faster.

import numpy as np

a = np.zeros(10)         # First assign the array
a[:5] = np.ones(5)       # Put the first few elements at 1
a[[1, 9, 6]] = [2, 3, 5] # Assign the values

Note the difference in the indexing since matlab's array start from 1 and python's from 0.

B: Dynamically append to the array

This method is takes longer and is more complex. I would only use it if you have no way of know from the start the complete size of your array:

import numpy as np

# Creat original array
a = np.ones(5)

# Define before hand which indices and values should be added
idx_to_add = [1, 9, 6]
values = [2, 3, 5]

# Loop over indice-values pairs to add them
for i, val in zip(idx_to_add, values):
    
    # If index is in array perform normal assignment
    if i < len(a):
        a[i] = val

    # Else extend the array
    else:
        extension = zeros(i - len(a) + 1)  # Build the array to append
        extension[i-len(a)] = val          # Assign the new value
        a = np.append(a, extension)        # Append the extension to a

As you see this is more complex to write but should still work. There might be some extra tricks to reduce a bit the number of lines of code here and there (I didn't use them for clarity) but the general idea stays the same.

Final note

I'll just finish by mentioning that, although the matlab syntax you're using is very short, it is slower. It is good practice to apply something similar to the first thing I suggest in python, where you create the whole array at first and then simply fill it. Your code will be much faster if you can do so.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LNiederha