# Extract variable rows and columns from a matrix

35 views (last 30 days)
Steve Rogers on 28 Jul 2020
I wish to input a variable row and column to extract a row length vector from a matrix at each update.
A small example input matrix is:
A = 0.0975 0.9649 0.4854 0.9157 0.0357 0.7577
0.2785 0.1576 0.8003 0.7922 0.8491 0.7431
0.5469 0.9706 0.1419 0.9595 0.9340 0.3922
0.9575 0.9572 0.4218 0.6557 0.6787 0.6555
I wish to extract a row variable, where row length is the number of column(6) of A and the row may range from 1 to 4.
An example follows:
A(row) = A([2 4 3 2 1 3]) = [0.2785 0.9572 0.1419 0.7922 0.0357 0.3922].
Although I can brute force it with a for loop, that is probably not efficient for a matrix column size in the hundreds.
[nr,nc] = size(A);row = [2 4 3 2 1 3];
for i = 1:nc
extract_vec(i) = A(row(i),i);
end
I prefer a method that takes advantage of matlab's matrix operations.

madhan ravi on 28 Jul 2020
A(sub2ind([nr, nc], rows, 1:nc))

R2020a

### Community Treasure Hunt

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

Start Hunting!