Page-wise Diagonalization?
显示 更早的评论
Does anyone know a fast way to do a page-wise diagonalization? I have an array A of size [n,1,m] and want an array B of size [n,n,m] where the diagonals of B are the orignal vectors of A. I know I can call diag(A(:,1,i)) in a loop but that is time inefficent, and I can't use pagefun because the school I get my liscense from blocks it for some reason. Any good ideas on how to do this?
采纳的回答
更多回答(2 个)
Ram Sreekar
2023-6-29
Hi Ty Clements,
As per my understanding, you want to perform page-wise diagonalization of a matrix ‘A’ of dimension [n, 1, m] such that the resulting matrix ‘B’ (say) is of dimension [n, n, m] where every B(:, :, i) is a diagonal matrix such that the diagonal elements are vectors A(:, :, i) for all i=1 to m.
You can refer to the example code given below.
% Example input array A of size [n,1,m]
A = rand(3, 1, 2);
% Get the size of A
[n, ~, m] = size(A);
% Create a 3D identity matrix of size [n, n, m]
I = repmat(eye(n), 1, 1, m);
% Perform element-wise multiplication between A and I using bsxfun
B = bsxfun(@times, A, I);
% Reshape B to size [n, n, m]
B = reshape(B, n, n, m);
Here, the ‘repmat’ function is used to create a matrix I of dimension [n, n, m] where every I(:, :, i) for i=1 to m is an Identity matrix.
The ‘bsxfun’ function is used to perform element-wise multiplication of A and I.
You can refer to links given below for detailed explanation of both the functions ‘repmat’ and ‘bsxfun’.
Hope this helps you resolve your query.
1 个评论
If you're using bsxfun(), there's no need to use repmat; also, there's no need to reshape the result.
n = 1000;
m = 100;
A = randi(9,n,1,m);
tic
% original method
B0 = zeros(n,n,m);
for k = 1:m
B0(:,:,k) = diag(A(:,1,k));
end
toc
tic
% Create a 3D identity matrix of size [n, n, m]
I = repmat(eye(n), 1, 1, m);
% Perform element-wise multiplication between A and I using bsxfun
B1 = bsxfun(@times, A, I);
% Reshape B to size [n, n, m]
B1 = reshape(B1, n, n, m);
toc
tic
% cuts the time in half
B2 = bsxfun(@times, A, eye(n));
toc
tic
% implicit array expansion works without bsxfun() since R2016b
B3 = A.*eye(n);
toc
isequal(B1,B0)
isequal(B2,B0)
isequal(B3,B0)
A=rand(4,1,3); pagetranspose(A)
[n,~,p]=size(A);
B=zeros(n^2,p);
B(1:n+1:end,:)=reshape(A,n,p);
B=reshape(B,n,n,p)
类别
在 帮助中心 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!