indexing diagonals out of a 3d matrix

34 ビュー (過去 30 日間)
Alberto Navarro
Alberto Navarro 2013 年 7 月 9 日
I thought this would be fairly simple. I thought the diag function should be able to do this task. I have a 14x14x1045 matrix Ht, t=1,...,1045 simbolizes the number of observations. I merely want to extract the main daigonals of Ht for all t and store them in a new 3d matrix Dt which is also 14x14x1045 which contains the diagonal elements of every Ht and zeros in all other positions. However, when using the function diag(Ht) I get the following error: Error using diag First input must be 2D.
Is there a function that works like diag but for 3d matrices? I have no experience programing any functions. Could someone please provide a simple loop to make a function that fulfills this task in case no such function exists already?
I´m sorry if this question is too trivial, but I haven´t been able to find a specific answer and I seem not to be able to program such a function with my expertise level...
Thanks a lot for your help!

採用された回答

Matt J
Matt J 2013 年 7 月 9 日
編集済み: Matt J 2013 年 7 月 9 日
D=bsxfun(@times, eye(size(H(:,:,1))), H)
  2 件のコメント
Matt J
Matt J 2013 年 7 月 9 日
編集済み: Matt J 2013 年 7 月 9 日
You could also use ndSparse (Available Here) to improve memory efficiency,
D=bsxfun(@times, ndSparse(speye(size(H(:,:,1)))), H);
Alberto Navarro
Alberto Navarro 2013 年 7 月 9 日
Great! Thanks a lot for the super fast and efficient answer!
Best regards!

サインインしてコメントする。

その他の回答 (2 件)

Evan
Evan 2013 年 7 月 9 日
編集済み: Evan 2013 年 7 月 9 日
A = rand(14,14,1045);
B = A(logical(repmat(eye(size(A(:,:,1))),[1 1 size(A,3)])))

Kiran Sagar
Kiran Sagar 2013 年 7 月 9 日
I think this would work elegantly. But I don't know if this would take up alot of time/memory for your purposes.
for i=1:1045
Dt(:,:,i)=diag(diag(Ht(:,:,i)));
end
  1 件のコメント
Alberto Navarro
Alberto Navarro 2013 年 7 月 9 日
Memory/time wasn´t an issue. That worked fine as well. I solved it with the first answer, but with this one, I now know how to use the for loop in the command window. Thanks for the suggestion!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by