Diagonal displacement of matrix into another matrix
3 次查看(过去 30 天)
显示 更早的评论
Hi,
I have this matrix 2X8:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/371389/image.png)
and from this I need to create 4 matrices of zeros 5X5 where I displace the 2X8 matrix thi way:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/371386/image.png)
Note that I have to do this parametrically so that if for exaple I have a matrix 2X10 it needs to be dsiplaced in 5 matrices 6X6 and so on.
Any suggestions?
8 个评论
Adam Danz
2020-10-6
Got it. Looks like Matt J and I answered at nearly the same time.
His approach puts the output matrices into a cell array. To access output matrix number n in his answer,
outputMatrices{n}
My approach stores the output matricies within a 3D array. To access output matrix number n in my answer,
A(:,:,n)
采纳的回答
更多回答(3 个)
Adam Danz
2020-10-6
编辑:Adam Danz
2020-10-6
Fast & efficient vectorized method
m is the input matrix size 2xN where N is divisible by 2.
A is the output array containing the N/2 matrices along the third dimension.
% m = reshape(1:16,2,8);
m = reshape(1:20,2,10)
% determine the linear index for the first 4 values (baseIdx)
nMat = size(m,2)/2;
matSize = [nMat,nMat]+1;
baseIdx = [1 2, matSize+[1,2]];
% determine the linear index of all values of m into A (Aidx)
A = nan([matSize,nMat]);
interval = 0: prod(matSize)+matSize(1)+1 : numel(A);
Aidx = baseIdx' + interval;
% Place values of m into A
A(Aidx) = m
0 个评论
Bruno Luong
2020-10-6
Simple loop would be the simplest for me
% Test matrix
A=randi(10,2,8)
n = size(A,2)/2
B = zeros(n+1,n+1,n);
for k=1:n
i = k+(0:1);
j = 2*k+(-1:0);
B(i,i,k) = A(:,j);
end
B
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!