How to extract diagonal elements of multidimensional array ?
12 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
shuang Yang
am 23 Mär. 2023
Kommentiert: Mattia Marsetti
am 24 Mär. 2023
If I have a m-order n-dimensional tensor. How should I extract the diagonal elements ?
For example
% Generate a 3-order 4-dimensional tensor
rng('default')
A = rand(4,4,4)
The diagonal elements are A(1,1,1) = 0.8147, A(2,2,2) = 0.0357, A(3,3,3) = 0.7655 and A(4,4,4) = 0.6991.
I was hoping to have a tensor_diag function that takes a tensor A as an input parameter and returns a vector consisting of its diagonal elements.
3 Kommentare
Stephen23
am 23 Mär. 2023
Bearbeitet: Stephen23
am 23 Mär. 2023
@Mattia Marsetti: your code throws an error on the example array:
rng('default')
A = rand(4,4,4)
get_tensor(A)
function out=get_tensor(v)
size_v=size(v);
if sum(size_v == size_v(1))<numel(size_v)
error('the input vector is not a sqare matrix');
end
N = size_v(1);
out=zeros(N,1);
for i=1:N
str='v(';
for s=1:N
str=[str 'i,'];
end
str(end:end+1)=');';
out(i)=eval(str);
end
end
Note that you could easily replace the evil EVAL with a cell array and a comma-separated list.
Akzeptierte Antwort
the cyclist
am 23 Mär. 2023
rng('default')
N = 4;
A = rand(N,N,N);
A(1:N^2+N+1:end)
5 Kommentare
the cyclist
am 23 Mär. 2023
Ah, I read your question too quickly, and didn't make my solution general enough. Glad you found it.
Stephen23
am 23 Mär. 2023
@shuang Yang: you could generalize that:
A(1:sum(N.^(0:ndims(A)-1):end)
Weitere Antworten (1)
Bruno Luong
am 23 Mär. 2023
N = 7;
A = rand(N,N,N,N,N);
p=ndims(A);
N=length(A);
% Method 1: generalization of cyclist's answer
step = polyval(ones(1,p),N);
idx = 1:step:N^p;
A(idx)
% Method 2
c = repmat({1:N}, [1,p]);
idx = sub2ind(size(A), c{:});
A(idx)
0 Kommentare
Siehe auch
Kategorien
Mehr zu Operating on Diagonal Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!