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

8 次查看(过去 30 天)
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 个评论
Matt J
Matt J 2023-6-28
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.

请先登录,再进行评论。

回答(3 个)

Matt J
Matt J 2023-6-28
编辑:Matt J 2023-6-28
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 2023-6-28
[~,n,p] = size(A);
[J,K] = ndgrid(1:n,1:p);
B = accumarray([J(:) J(:) K(:)], A(:), [n,n,p]);

shobun
shobun 2023-8-10
A.*eye(20)
  6 个评论
shobun
shobun 2023-8-10
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by