Extract diagonal element from each frontal slice of tensor

前端 未结 3 933
忘掉有多难
忘掉有多难 2021-01-19 10:55

I have a p-by-p-by-n tensor. I want to extract diagonal element for each p-by-p slice. Are there anyone know how to do this without looping?

Thank you.

3条回答
  •  盖世英雄少女心
    2021-01-19 11:28

    Just reading Divakar's answer and trying to understand why he again is roughly 10 times faster than my idea I put together code mixing both, and ended up with code which is faster:

    A=reshape(A,[],n);
    diags2 = A(1:p+1:p*p,:);
    

    For a 500x500x500 tensor I get 0.008s for Divakar's solution and 0.005s for my solution using Matlab 2013a. Probably plain indexing is the only way to beat bsxfun.

提交回复
热议问题