0

I have a statement in my Matlab code:

a = find(abs(ASE_lamda-YDFA_lam_s)<1e-15);

After to execution I get the output as:

octave:50> whos a
Variables in the current scope:

   Attr Name        Size                     Bytes  Class
   ==== ====        ====                     =====  ===== 
        a           1x1                          8  double

Total is 1 element using 8 bytes

octave:51> a
a =  33

I have migrated the code to Python using NumPy package in below method:

a = np.nonzero(np.abs(ASE_lamda-YDFA_lam_s)<1e-15)

But the type of variable a is tuple

(array([32]),)

What is the correct way to migrate the above code?

0

1 Answer 1

2

They are equivalent. As you can see your Matlab/Octave code returned the 1x1 dimensional matrix a = 33 while NumPy gave you the 1-dimensional vector a = [32].

The reason it is a tuple is because nonzero gives you a tuple of indices for each dimension. If you are dealing with 1-dimensional data (which is probably the case here) you could look into using numpy.flatnonzero instead.

I think the confusion is that Octave (and probably Matlab as well) treats the 1x1 matrix as a scalar, while NumPy does not.

So, to get the single entry you just take the first (and only) element by normal indexing:

a = a[0]

Something that will probably bite you when moving between Matlab and NumPy is that the former is a lot more lenient on indexing and matrix shapes. In NumPy there is a difference between an array of shape (N,) and (N, 1) which you will probably run into when e.g. multiplying matrices.

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

3 Comments

It's not so much that MATLAB is more lenient, but that a 2d matrix is its base type. At one time (v 3.0) that's all there was.
@hpaulj, Yeah, sure. I was mostly aiming at the fact that NumPy sometimes gives you weird results if you are not careful. There is a difference between multiplying a (2,) array and a (2,) array and a (2,1) and (1,2) array. The former gives the expected (2,) array as result, while the latter gives you a (2,2) array, which is probably not what you wanted most times.
Though I've often done something like x=[1,2]; y=x.'*x. And now that Octave does numpy-like broadcasting x.' .* x produces the same thing.

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.