Convert Matlab Sum Function with ~= Not Equal Condition to Python

Convert Matlab Sum Function with ~= Not Equal Condition to Python

I want to convert this sum(sum(W_set{1}~=0)) into Python:

%MATLAB code:
W_set = {[[[-0.05747274, -0.05268928],
         [-0.10961724,  0.10119643],
         [-0.0327577 ,  0.01514941]]],
      
         [[[-0.05557293,  0.11311244],
         [-0.22935626, -0.11837874],
         [-0.05567432, -0.0558801 ]]]};

sum(sum(W_set{1}~=0))

The output is 6. how can I get this output in Python, W_set in Python is a list.

I have tried the following approach, but the result is not the same.

#Python code:
import numpy as np
W_set = [[[[-0.05747274, -0.05268928],
         [-0.10961724,  0.10119643],
         [-0.0327577 ,  0.01514941]]],
      
         [[[-0.05557293,  0.11311244],
         [-0.22935626, -0.11837874],
         [-0.05567432, -0.0558801 ]]]]

if np.array(W_set[0]).all != 0:    #checking not equal to zero
  sum_ = np.sum(np.sum(W_set[0]))  #sum
print(sum_)

The answer is -0.13619112. What is the meaning of operator ~= when used in the MATLAB sum function?

3

1 Answer

You can use numpy.sum it will sum over all the axis, but in order to compare the elements to zero in a vectorized instruction you need it to be a numpy array

np.sum(np.array(W_set[0]) != 0)

Alternatively you could have made W_set = np.array([...]) and then

np.sum(W_set[0] != 0)
(W_set[0] != 0).sum()
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.