I am a recent immigrant to the world of Python. I need to figure out how to copy a matrix to a larger matrix in Python. Let me illustrate this with an example in Matlab:
A = randn(4,4);
B = eye(2,2);
A(1:2,1:2) = B
gives
A =
1.0000 0 3.5784 0.7254
0 1.0000 2.7694 - 0.0631
-2.2588 - 0.4336 - 1.3499 0.7147
0.8622 0.3426 3.0349 - 0.2050
I am trying a similar thing with Python using NumPy in the following fashion.
A = np.random.randn(4,4)
B = np.eye(2,2)
A[0:1,0:1] = B
gives
ValueError: output operand requires a reduction, but reduction is not enabled.
Of course, the simplest way to avoid this is to use a loop but I would want to keep it vectorized.
Can someone please point me to a way of doing this without using for loops?
Here’s the problem:
You want:
Why? Because Python uses half-open ranges. So the slice
[0:1]is the half-open range[0, 1), meaning just the index0; the slice[0:2]is the half-open range[0, 2), meaning the indices0and1.