I want to create the same result in Python and don't use any loop method.
Matlab code of what I want to do:
x = [1 2 3 4];
y = [1 2 3];
z = 2.^(x'-y)
The result of this Matlab code:
z =
1.0000 0.5000 0.2500
2.0000 1.0000 0.5000
4.0000 2.0000 1.0000
8.0000 4.0000 2.0000
Is there any good Python method for doing so?
I'm confused about this for a long time...
CodePudding user response:
You will want to use numpy for this. It will do array based numerical operations similar to what you are used to with Matlab.
Note the use of np.newaxis to increase the dimensions of x
so that array broadcasting will work correctly. Broadcasting is similar to implicit expansion in Matlab.
Also, the dot is this 2.
does not serve the same purpose as in Matlab (indicating element-wise operation). This is just to force the 2
to be a float. Otherwise, you will get errors about raising integers to negative integers.
import numpy as np
x = np.array([1, 2, 3, 4])
y = np.array([1, 2, 3])
z = 2.**(x[:,np.newaxis]-y)
array([[1. , 0.5 , 0.25],
[2. , 1. , 0.5 ],
[4. , 2. , 1. ],
[8. , 4. , 2. ]])