how to convert H(b < g) = 2*100 – H(b < g) from MATLAB to python
Question:
I have the MATLAB code like below
H = [10 20 30 40 50 60]
b = [5 9 28 59 22 18]
g = [9 9 10 25 30 5]
H(b < g) = 2*100 - H(b < g)
the result is like this :
H =
190 20 30 40 150 60
I think this code means that if b[index] < g[index]
then H[index] = 2*100 - H[index]
Is my understanding is correct?
Is there way in python to do it without looping for the index?
Answers:
To make it in just one line.
If b
or g
are too short, this code will raise an exception.
H = [2*100 - h if b[inx] < g[inx] else h
for inx, h in enumerate(H)]
As have already been said in the comments, if you have a lot of code from Matlab to "translate" into Python, you better use numpy
.
Your understanding of the code is correct: the MATLAB code checks which elements of b
are less than the corresponding element of g
, and changes only those corresponding elements of H
to 200 - H
.
Since you’re already using numpy
, translating MATLAB is quite straightforward: just change the parentheses to brackets.
H = np.array([10, 20, 30, 40, 50, 60])
b = np.array([5, 9, 28, 59, 22, 18])
g = np.array([9, 9, 10, 25, 30, 5])
H[b < g] = 2*100 - H[b < g]
Which gives the desired H
:
array([190, 20, 30, 40, 150, 60])
Here’s a handy resource for translating MATLAB to numpy: https://numpy.org/doc/stable/user/numpy-for-matlab-users.html
I have the MATLAB code like below
H = [10 20 30 40 50 60]
b = [5 9 28 59 22 18]
g = [9 9 10 25 30 5]
H(b < g) = 2*100 - H(b < g)
the result is like this :
H =
190 20 30 40 150 60
I think this code means that if b[index] < g[index]
then H[index] = 2*100 - H[index]
Is my understanding is correct?
Is there way in python to do it without looping for the index?
To make it in just one line.
If b
or g
are too short, this code will raise an exception.
H = [2*100 - h if b[inx] < g[inx] else h
for inx, h in enumerate(H)]
As have already been said in the comments, if you have a lot of code from Matlab to "translate" into Python, you better use numpy
.
Your understanding of the code is correct: the MATLAB code checks which elements of b
are less than the corresponding element of g
, and changes only those corresponding elements of H
to 200 - H
.
Since you’re already using numpy
, translating MATLAB is quite straightforward: just change the parentheses to brackets.
H = np.array([10, 20, 30, 40, 50, 60])
b = np.array([5, 9, 28, 59, 22, 18])
g = np.array([9, 9, 10, 25, 30, 5])
H[b < g] = 2*100 - H[b < g]
Which gives the desired H
:
array([190, 20, 30, 40, 150, 60])
Here’s a handy resource for translating MATLAB to numpy: https://numpy.org/doc/stable/user/numpy-for-matlab-users.html