How to superimpose a matrix?
34 views (last 30 days)
Show older comments
Two matrices (y and z, both are 2 x 2 matrix) are to be added to obtain third matrix (i.e. matrix 'x') which is 3x3.
However, x should be [ 1 -1 0; -1 2 -1; 0 -1 1]. Such that common index gets added and gives a final sum.
y = [1 -1; -1 1]
z = [1 -1; -1 1]
2 Comments
Accepted Answer
KSSV
on 4 Feb 2020
Edited: KSSV
on 4 Feb 2020
m = 5 ;
k0 = [1 2 2 2 1] ; % diagonal elements
k1 = -1*ones(1,m-1) ; % above and below main diagonal elements
iwant = diag(k1,-1)+diag(k0)+diag(k1,1) ;
2 Comments
KSSV
on 4 Feb 2020
w = [1 -1; -1 1]
x = w ;
y = w ;
z = w ;
W = zeros(5) ; W(1:2,1:2) = w ;
X = zeros(5) ; X(2:3,2:3) = x ;
Y = zeros(5) ; Y(3:4,3:4) = y ;
Z = zeros(5) ; Z(4:5,4:5) = z ;
iwant = W+X+Y+Z ;
More Answers (1)
Jesse Cole
on 17 Mar 2021
I am working on something similiar for my needs. In my case I have a series of N=5 4x4 matrices that I need to superimpose to form a larger matrix. I need to superimpose matrices such that my first matrix M1 begins in the 1,1 position on the resultant matrix R, the rest of M1 would populate the resultant matrix to fill out the 4x4 (m x m) chunk. The next matrix to superimpose (add to the resultant matrix) needs to start at the 2,2 position in the resultant matrix R and populate a 4x4 chunk, adding to any values that are already in the resultant matrix. This must continue for all N matrices, where matrices start on the i,i position on resultant diagonal and populate. I want to execute this without manually typing everuthing out. I'll use a for loop.
For demonstration: Each matrix to be superimposed is mxm. Using a for loop, we could fill out each mxm matrix by looping through m rows and m columns to create a copy the m x m matrix M1 into the matrix R.
for b = 1:m
for k = 1:m
R(b,k) = M1(b,k)
end
end
But I have a series of N m x m matrices. I will put them in an array. I use a cell array, k where I have N = 5 matrices to superimpose.
k = {M1 M2 M3 M4 M5}
I use this cell array so that I can use the index in the for loop to iterate throught each matrix. The final superimposition will use a for loop as follows. Note that if I have N = 5, 4 x 4 (m x m) matrices to superimpose, then my final resultant matrix R will have size 8x8 or (N+(m-1)). Preallocate the R matrix outside the loop. You could use this for any N, or m values.
TLDR
sizeR = 8 % the size of R is 8 = N+(m-1) = 5+(4-1)
m = 4 % size of the matrices to superimpose
R = zeros(sizeR)
for i = 1:5 % i = 1:N this index loops through the cell array, k
T = zeros(sizeR) % size of temporary matrix = size of R so they will add
T(i:i+(m-1),i:i+(m-1)) = k{i} % sets the area chunk of T = matrix to be imposed
R = R+T % Add the matrices to superimpose
end
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!