Access to array elements

1 visualizzazione (ultimi 30 giorni)
Ana
Ana il 14 Nov 2011
Hi,
I have a matrix, A, and I want to access the elements given by the vectors ind_rows, ind_cols. If I make A(ind_rows,ind_cols) I get a matrix of size ind_rows times ind_cols, but I am just interested in the diagonal of this matrix!
I have found a way to do this:
siz = size(A);
AA = A(1:end); % convert the matrix in a vector
IND = sub2ind(siz,ind_rows,ind_cols);
res = AA(IND);
It works, but I guess there must be a way to do this without rearranging the matrix in a vector, and in a cleaner way.
Thanks in advance!
Ana

Risposta accettata

Pavl M.
Pavl M. il 14 Nov 2011
  1 Commento
Ana
Ana il 14 Nov 2011
So I guess it would be enough with:
siz = size(A);
IND = sub2ind(siz,ind_rows,ind_cols);
res = A(IND);
Thank you!

Accedi per commentare.

Più risposte (1)

Image Analyst
Image Analyst il 14 Nov 2011
Ana: The most common way to get the diagonals is to use the eye() function:
m_DiagonalsOnly = m(logical(eye(size(m, 1))))
  1 Commento
Ana
Ana il 14 Nov 2011
The problem is that in some cases the matrix A(ind_rows,ind_cols) is too big to be generated, so I needed something that did not create that matrix.
Anyway I am not sure I am understanding properly your suggestion, since to get the diagonal of a matrix I can just simply the diag command, can't I?
Thank you.

Accedi per commentare.

Categorie

Scopri di più su Operating on Diagonal Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by