How to convert matrices from matlab to python?

I have the following code in Matlab that I am not familiar with:

function segments = segmentEnergy(data, th)
    mag = sqrt(sum(data(:, 1:3) .^ 2, 2));
    mag = mag - mean(mag);

    above = find(mag>=th*std(mag));
    indicator = zeros(size(mag));
    indicator(above) = 1;
    plot(mag); hold on; plot(indicator*1000, 'r')
end

I wrote this following function in Python:

def segment_energy(data, th):
    mag = np.linalg.norm((data['x'], data['y'], data['z']))
    print "This is the mag: " + str(mag)
    mag -= np.mean(mag)

    above = np.where(mag >= th * np.std(mag))
    indicator = np.zeros(mag.shape)
    indicator[above] = 1
    plt.plot(mag)
    plt.plot(indicator * 1000, 'r')
    plt.show()

I get an error message:

line 23, in segment_energy
indicator[above] = 1
IndexError: too many indices for array

datais pandas DataFrame, which was read from a CSV file containing data on three-way accelerometers. Axis of accelerometer data x, yand z. The columns for the data frame timestamp, time skipped, x, y, zand labelin that order.

The error is that magPython is a scalar in code, and I view it as a matrix. However, I'm not sure how they turn magthe matrix into MATLAB functions.

+6
1

numpy.linalg.norm , . mag , , , :

  • 0 (.. mag <- mag - np.mean(mag) --> 0).

  • above . NumPy 1, 0, , "", , . , 0, np.std.

  • shape undefined, : (). , numpy.mean, mag.shape , NumPy. np.mean NumPy.

    :

    In [56]: mag = 10
    
    In [57]: type(mag)
    Out[57]: int
    
    In [58]: mag -= np.mean(mag)
    
    In [59]: type(mag)
    Out[59]: numpy.float64
    
  • , indicator , , , .

, , mag ... ... 10 th = 1:

In [60]: mag = 10

In [61]: mag -= np.mean(mag)

In [62]: mag.shape
Out[62]: ()

In [63]: th = 1

In [64]: above = np.where(mag >= th * np.std(mag))

In [65]: indicator = np.zeros(mag.shape)

In [66]: indicator
Out[66]: array(0.0)

In [67]: mag
Out[67]: 0.0

In [68]: indicator[above] = 1
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-67-adf9cff7610a> in <module>()
----> 1 indicator[above] = 1

IndexError: too many indices for array

, - , . MATLAB , data , . , pandas DataFrame, numpy, , MATLAB. , x, y z , numpy, .

def segment_energy(data, th):
    mag = np.sqrt(np.sum(data.loc[:, ['x','y','z']]** 2.0, axis=1)) # Change
    mag = np.array(mag) # Convert to NumPy array
    mag -= np.mean(mag)

    above = np.where(mag >= th * np.std(mag))
    indicator = np.zeros(mag.shape)
    indicator[above] = 1
    plt.plot(mag)
    plt.plot(indicator * 1000, 'r')
    plt.show()

- MATLAB NumPy. loc, pandas DataFrame , . NumPy, .

numpy.linalg.norm, , . 2D, axis=1, :

mag = np.linalg.norm(data.loc[:, ['x', 'y', 'z']], axis=1)

NumPy .

+3

All Articles