Extract numbers from matrix based on logical array

8 views (last 30 days)
I want to extract the numbers from a matrix 'x' using a logical array 'y':
x =
0.5853 0.2551 0.8909
0.2238 0.5060 0.9593
0.7513 0.6991 0.5472
y =
0 1 1
1 1 0
1 0 1
I want the solution to be in a 3x2 matrix, so something like this: z = [0.2551 0.8909; 0.2238 0.5060; 0.7513 0.5472].
If possible, no for loops should be used. I tried z=x(y==1), but that puts out a 6x1 matrix

Accepted Answer

dpb
dpb on 14 Apr 2023
x =[
0.5853 0.2551 0.8909
0.2238 0.5060 0.9593
0.7513 0.6991 0.5472].';
y =logical([
0 1 1
1 1 0
1 0 1]).';
N=sum(y);
assert(all(N==N(1)),'Unequal numbers selected')
z=reshape(x(y),N(1),[]).'
z = 3×2
0.2551 0.8909 0.2238 0.5060 0.7513 0.5472

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!