Extract numbers from matrix based on logical array

2 vues (au cours des 30 derniers jours)
RE
RE le 13 Avr 2023
Réponse apportée : dpb le 14 Avr 2023
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

Réponse acceptée

dpb
dpb le 14 Avr 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

Plus de réponses (0)

Catégories

En savoir plus sur Multidimensional Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by