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.

 채택된 답변

Paul Hoffrichter
Paul Hoffrichter 2020년 12월 31일

1 개 추천

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

댓글 수: 2

Paul Hoffrichter
Paul Hoffrichter 2020년 12월 31일
편집: Paul Hoffrichter 2020년 12월 31일
To test with another matrix:
B = [1 2 3; 4 5 6; 10 20 30; 40 50 60; 70 80 90];
sz = size(B);
fiB = @(x) sub2ind(sz, ceil( x/sz(2) ), rem(x-1, sz(2)) + 1);
yy = 1:numel(B);
B(fiB(yy))
ans =
Columns 1 through 8
1 2 3 4 5 6 10 20
Columns 9 through 15
30 40 50 60 70 80 90
A(fiA(5))
ans =
5
B(fiB(10))
ans =
40
Salahuddin Tariq
Salahuddin Tariq 2020년 12월 31일
Thanks for updating the other methods :) because I was aware that how to do it using the transponse matrix operation. Actually I wanted to avoid the usage of for loop while scanning the elements of matrix.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Paul Hoffrichter
Paul Hoffrichter 2020년 12월 30일
편집: Paul Hoffrichter 2020년 12월 30일

1 개 추천

A = [1 2 3; 4 5 6];
Atr = transpose(A);
Atr(1:6)
ans =
1 2 3 4 5 6

카테고리

도움말 센터File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by