Assigning array values to cell array based on condition
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Dominik Rhiem
el 13 de Dic. de 2021
Comentada: Dominik Rhiem
el 21 de Dic. de 2021
I have two equally-sized vectors of indices like the following:
A = [1, 1, 1, 2, 2, 3, 3, 3, 3];
B = [6, 3, 7, 4, 7, 13, 16, 4, 1];
I want to assign the values of B into cell arrays based on the value of A at the same index, i.e.:
C{1} = B(A==1);
C{2} = B(A==2);
C{3} = B(A==3);
In reality, A contains all integers from 1 to 1600 (monotonically increasing, but each integer appears a different number of times), so it is impractical to write all lines out. So far, I have solved this with a loop (in each iteration, I create the mask C = B(A==iteration)), but loops are inefficient, so are there better ways to do it?
Similarly, I want to use this to assign values to the elements of a vector v. For example:
v(1) = sum(M(C{1}));
v(2) = sum(M(C{2}));
Where M is some other large vector from which we select the relevant entries by the indices in C as indicated. Again, this is currently implemented as a loop (i.e. v(i) = sum(M(B(A==i))) ), which works, but again, are there better ways to do it?
0 comentarios
Respuesta aceptada
Stephen23
el 13 de Dic. de 2021
Editada: Stephen23
el 13 de Dic. de 2021
A = [1,1,1,2,2,3,3,3,3];
B = [6,3,7,4,7,13,16,4,1];
C = accumarray(A(:),B(:),[],@(v){v});
C{:}
For the second part of your question I would skip the cell array entirely:
M = randi(9,1,20);
V = accumarray(A(:),M(B(:)),[],@sum)
2 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrices and Arrays en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!