1

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.

1
  • Not a Python person, so I'm not posting a answer, but this looks like "sqrt(eigenvalues)[newaxis,:]" would go to something like "diag(eigenvalues)" converting a vector to a matrix. Commented Sep 24, 2022 at 10:57

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.