MATLAB: Reading the matrix elements row wise

indexingmatrices

Let say I have a matrix A = [1 2 3; 4 5 6], I can access its elements by writing A(1) and A(2) etc. but this index runs column wise. How to access elements of matrix row by row, for example if I write A(2), I want to get 2 and not 4.

Best Answer

If you do not want to take the transpose of the A matrix, you can work with the subscripts instead.
A = [1 2 3; 4 5 6];
sz = size(A);
fiA = @(x) sub2ind(sz, ceil( x/sz(2) ), rem(x-1, sz(2)) + 1);
xx = 1:numel(A);
A(fiA(xx))
ans =
1 2 3 4 5 6