Page-wise Diagonalization?
Show older comments
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?
Accepted Answer
More Answers (2)
Ram Sreekar
on 29 Jun 2023
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 Comment
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)
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!