Home > Mobile >  Convert statement from Numpy to Matlab
Convert statement from Numpy to Matlab

Time:09-27

I'm translating a Python class to Matlab. Most of it is straightforward, but I'm not so good with Python syntax (I hardly ever use it). I'm stuck on the following:

# find the basis that will be uncorrelated using the covariance matrix
basis = (sqrt(eigenvalues)[newaxis,:] * eigenvectors).transpose()

Can someone help me figure out what the equivalent Matlab syntax would be?

I've found via Google that np.newaxis increases the dimensionality of the array, and transpose is pretty self explanatory. So for newaxis, something involving cat in matlab would probably do it, but I'm really not clear on how Python handles arrays TBH.

CodePudding user response:

Assuming eigenvalues is a 1D array of length N in Python, then sqrt(eigenvalues)[newaxis,:] would be a 1xN array. This is translated to MATLAB as either sqrt(eigenvalues) or sqrt(eigenvalues).', depending on the orientation of the eigenvalues array in MATLAB.

The * operation then does broadcasting (in MATLAB this is called singleton expansion). It looks like the operation multiplies each eigenvector by the square root of the corresponding eigenvalue (assuming eigenvectors are the columns).

If in MATLAB you computed the eigendecomposition like this:

[eigenvectors, eigenvalues] = eig(A);

then you’d just do:

basis = sqrt(eigenvalues) * eigenvectors.';

or

basis = (eigenvectors * sqrt(eigenvalues)).';

(note the parentheses) because eigenvalues is a diagonal matrix.

  • Related