How to extract and store parts of a matrix to new matrices

Illustration
Emersondesouza - 2020-08-18T15:16:43+00:00
Question: How to extract and store parts of a matrix to new matrices

I have read the FAQ to extract parts of an existing matrix to new matrices only by selection of rows but had no success. I wish to do the following: Let M= 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 and the following parameters to create a loop: for k=1:3; l=(k+1); m=(2*k)+3; mk=M(l:m,1:end); end; I wished by doing that above to get the following results for k=1 m1= 2 2 3 3 4 4 5 5 for k=2 m2= 3 3 4 4 5 5 6 6 7 7 for k=3 m3= 4 4 5 5 6 6 7 7 8 8 9 9 and so on. Instead, as result I obtained only: mk= 4 4 5 5 6 6 7 7 8 8 9 9 It is only the matrix for the last value of k and the index 3 is not appearing instead of k for mk. Hopefully someone knows how to fix this problem  

Expert Answer

Profile picture of John Williams John Williams answered . 2025-11-20

In your loop, you are writing to the single variable "mk" over and over again, overwriting the value from the previous loop. Probably the best way to do this is with a "cell array". Each element of the cell array can itself be an array, which is what you want.

Use

 

 mk{k}=M(l:m,1:end);

inside the loop, where the "k" inside the curly brackets indexes into the cell array. When you are done, your mk variable will have three elements; each will be an array.


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!