Clear Filters
Clear Filters

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

1 view (last 30 days)
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 Comment
Alejandro Fernández
Alejandro Fernández on 2 Feb 2021
Edited: Alejandro Fernández on 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.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 2 Feb 2021
Edited: Stephen23 on 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

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!