Search code examples
matlabmatrixrandomsubmatrix

Create a submatrix using random columns and loop


I have a 102-by-102 matrix. I want to select square sub-matrices of orders from 2 up to 8 using random column numbers. Here is what I have done so far.

matt is the the original matrix of size 102-by-102.

ittr = 30
cols = 3;
for i = 1:ittr
   rr = randi([2,102], cols,1);
   mattsub = matt([rr(1) rr(2) rr(3)], [rr(1) rr(2) rr(3)]);
end

I have to extract matrices of different orders from 2 to 8. Using the above code I would have to change the mattsub line every time I change cols. I believe it is possible to do with another loop inside but cannot figure out how. How can I do this?


Solution

  • There is no need to extract elements of a vector and concatenate them, just use the vector to index a matrix.

    Instead of :

    mattsub = matt([rr(1) rr(2) rr(3)], [rr(1) rr(2) rr(3)]);
    

    Use this:

    mattsub = matt(rr, rr);