how to solve diagonal matrix of each page of a 3D vector ? pagediag?

6 Ansichten (letzte 30 Tage)
Jiawen Luo
Jiawen Luo am 28 Jun. 2023
Kommentiert: Bruno Luong am 10 Aug. 2023
There is a 3D vector A, it has 100 pages, each page is a 1×20 vector. I want to solve diagonal matrix of each 1×20 vector.
A=rand(1,20,100);
for k=1:100
B(:,:,k)=diag(A(:,:,k));
end
B is a 20×20×100 matrix.
I'm trying to vectorize this expression, is there a matlab function maybe called 'pagediag' that can solve B=pagediag(A) ?
  1 Kommentar
Matt J
Matt J am 28 Jun. 2023
I am concerned about why you think you need a pagediag.If you plan to use it in conjunction with pagemtimes to scale the rows or columns of a stack of matrices, it's the wrong approach.

Melden Sie sich an, um zu kommentieren.

Antworten (3)

Matt J
Matt J am 28 Jun. 2023
Bearbeitet: Matt J am 28 Jun. 2023
A=rand(1,4,3)
A =
A(:,:,1) = 0.0986 0.2790 0.2407 0.2268 A(:,:,2) = 0.4894 0.0108 0.5699 0.2451 A(:,:,3) = 0.5105 0.6127 0.1543 0.3238
[~,n,p]=size(A);
B=zeros(n^2,p);
B(1:n+1:end,:)=reshape(A,n,p);
B=reshape(B,n,n,p)
B =
B(:,:,1) = 0.0986 0 0 0 0 0.2790 0 0 0 0 0.2407 0 0 0 0 0.2268 B(:,:,2) = 0.4894 0 0 0 0 0.0108 0 0 0 0 0.5699 0 0 0 0 0.2451 B(:,:,3) = 0.5105 0 0 0 0 0.6127 0 0 0 0 0.1543 0 0 0 0 0.3238

Bruno Luong
Bruno Luong am 28 Jun. 2023
[~,n,p] = size(A);
[J,K] = ndgrid(1:n,1:p);
B = accumarray([J(:) J(:) K(:)], A(:), [n,n,p]);

shobun
shobun am 10 Aug. 2023
A.*eye(20)
  6 Kommentare
shobun
shobun am 10 Aug. 2023
Thanks!
for column vectors
A=rand(3,1,5)
A =
A(:,:,1) = 0.2270 0.3032 0.1406 A(:,:,2) = 0.7674 0.6613 0.2126 A(:,:,3) = 0.3058 0.1203 0.2630 A(:,:,4) = 0.9825 0.3091 0.3544 A(:,:,5) = 0.7992 0.5751 0.6762
diagA=eye(3).*A
diagA =
diagA(:,:,1) = 0.2270 0 0 0 0.3032 0 0 0 0.1406 diagA(:,:,2) = 0.7674 0 0 0 0.6613 0 0 0 0.2126 diagA(:,:,3) = 0.3058 0 0 0 0.1203 0 0 0 0.2630 diagA(:,:,4) = 0.9825 0 0 0 0.3091 0 0 0 0.3544 diagA(:,:,5) = 0.7992 0 0 0 0.5751 0 0 0 0.6762

Melden Sie sich an, um zu kommentieren.

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!

Translated by