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

1 Ansicht (letzte 30 Tage)
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 Kommentar
Alejandro Fernández
Alejandro Fernández am 2 Feb. 2021
Bearbeitet: Alejandro Fernández am 2 Feb. 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 2 Feb. 2021
Bearbeitet: Stephen23 am 2 Feb. 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 Kommentar
Alejandro Fernández
Alejandro Fernández am 2 Feb. 2021
Wow, amazing! That's easier than any of the ideas I could have come up with, thank you a million times over!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Data Type Identification finden Sie in Help Center und File Exchange

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by