0

I have the following logic operation coded in MATLAB, where [A, B, C, and D] are all 5x3x16 doubles and [a, b, c, and d] are all 240x1 doubles. I am trying to implement the same logic operation in python using numpy.

D = zeros(size(A)); 
for i = 1:numel(D)
    flag = ...
        (a == A(i)) & ...
        (b == B(i)) & ...
        (c == C(i));
    D(i) = d(flag);
end

d is a column vector that is already populated with data. a, b, and c are also populated column vectors of equal size. Meshgrid was used to construct A, B, and C into a LxMxN grid of the unique values within a, b, and c. Now I want to use d to populate a LxMxN D with the appropriate values using the boolean expression.

I have tried:

D= np.zeros(np.shape(N))
for i in range(len(D)):

    for j in range(len(D[0])):

        for k in range(len(D[0][0])):    
            flag = np.logical_and(                                  
                (a == A[i][j][k]),              
                (b == B[i][j][k]),        
                (c == C[i][j][k])
                )
            D[i][j][k] = d[flag];
4
  • Possible duplicate of How to perform element wise boolean operations on numpy arrays Commented Mar 21, 2019 at 17:28
  • Welcome to the site. Please make sure to provide (cut down) sample data and target output. This will make it a lot easier to help. Commented Mar 21, 2019 at 17:45
  • I'm really not clear on what you want D to be at the end of this. Can you provide some example data (e.g. A, B, and C, as 2x2x2 and a, b, c, and d as 3x1) with what you'd like/expect the output to be? Commented Mar 21, 2019 at 22:51
  • @aganders3 It is hard to give an example but I will try to explain. d is a column vector that is already populated with data. a, b, and c are also populated column vectors of equal size. Meshgrid was used to construct A, B, and C into a LxMxN grid of the unique values within a, b, and c. Now I want to use d to populate a LxMxN D with the appropriate values using the boolean expression. Commented Mar 22, 2019 at 21:14

1 Answer 1

1

The syntax will be a little messier, but you can use the np.logical_* functions to do this.

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

7 Comments

Right. I thought that this function would do the trick. I have been struggling with the syntax.
Why not & and |?
@CrisLuengo I don't think it works the same with multidimensional np arrays. I get a ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
@MGoforth: here it says that should work.
@MGoforth: a=np.random.rand(10,12,6); b=(a>0.4)&(a<0.6) works for me.
|

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.