Convert matrix to cell knowing the number of components to have in each cell

1 visualización (últimos 30 días)
Hi, does anyone know how I could go from the data matrix to cell A knowing that, in this case:
idx = [2;4;3];
data = rand(9,2);
data =
0.7922 0.3922
0.9595 0.6555
0.6557 0.1712
0.0357 0.7060
0.8491 0.0318
0.9340 0.2769
0.6787 0.0462
0.7577 0.0971
0.7431 0.8235
- The first component of A will be the idx(1) 2 first elements of data.
- The second component of A will be the idx(2) next 4 elements of the array data
- The third component of A will be the next idx(3) 3 elements of the array data
In this case:
A{1} = [0.7922,0.3922;0.9595,0.6555];
A{2} = [0.6557,0.1712;0.0357,0.7060;0.8491,0.0318;0.9340,0.2769];
A{3} = [0.6787,0.0462;0.7577,0.0971;0.7431,0.8235];
  1 comentario
Alejandro Fernández
Alejandro Fernández el 2 de Feb. de 2021
Editada: Alejandro Fernández el 2 de Feb. de 2021
Another option to do it (which I wouldn't know either) would be, for example, to make a matrix that, based on idx that creates as many ones as elements indicated by idx(1), as many twos as elements indicated by idx(2),... as many x's as elements indicated by idx(end), in this case:
idx = [2;4;3];
B = [1;1;2;2;2;2;3;3;3];
Then a loop could be made so that the different elements could be separated in the corresponding cells.
It's just an idea since, as I said, I wouldn't know how to solve it that way either.

Iniciar sesión para comentar.

Respuesta aceptada

Stephen23
Stephen23 el 2 de Feb. de 2021
Editada: Stephen23 el 2 de Feb. de 2021
idx = [2;4;3];
data = [
0.7922 0.3922
0.9595 0.6555
0.6557 0.1712
0.0357 0.7060
0.8491 0.0318
0.9340 0.2769
0.6787 0.0462
0.7577 0.0971
0.7431 0.8235];
A = mat2cell(data,idx,2)
A = 3x1 cell array
{2×2 double} {4×2 double} {3×2 double}
A{:}
ans = 2×2
0.7922 0.3922 0.9595 0.6555
ans = 4×2
0.6557 0.1712 0.0357 0.7060 0.8491 0.0318 0.9340 0.2769
ans = 3×2
0.6787 0.0462 0.7577 0.0971 0.7431 0.8235
  1 comentario
Alejandro Fernández
Alejandro Fernández el 2 de Feb. de 2021
Wow, amazing! That's easier than any of the ideas I could have come up with, thank you a million times over!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Structures en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by