MATLAB: How can I extract matrix elements from 1 matrix that correspond to a 2 nd matrix and place them in a 3rd matrix

matrixvector

Hi, Can anyone help with this, I am trying to solve it without using for loops as it takes forever. I have 2 large 3D matrices. Matrix (A) has values from 0 to 5 and Matrix (B) just numbers from 1 to 100. They are the same size I want to find the elements of Matrix (A) that have a say a value 5 and extract the corresponding elements in Matrix (B) into a 3rd Matrix (C) which would also have the same size as (A) and (B)
I have tried to use C=B(ismember(A,5))
The ismember(B,5) gives me a 3D matrix but the result of (C) gives me a vector rather than a 3D matrix
thanks

Best Answer

Define C with a specific size first, then replace the appropriate elements. What you are doing is defining C as only those elements that satisfy the ismember call. E.g.,
C = zeros(size(B)); % <-- or whatever is appropriate for default values
x = ismember(A,5);
C(x) = B(x);