Matrix extension by inserting 0

I want to extend matrix by inserting 0 like uploaded picture.
How can I do?

 Accepted Answer

k2 = 1;
M1 = [k2 -k2 -k2 k2; 0 k2 k2 -k2; 0 0 k2 -k2; 0 0 0 k2];
M1_new = zeros(size(M1)+2);
M1_new([1 2 5 6],[1 2 5 6]) = M1;
disp(M1);
1 -1 -1 1 0 1 1 -1 0 0 1 -1 0 0 0 1
disp(M1_new);
1 -1 0 0 -1 1 0 1 0 0 1 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 1
k3 = 1;
M2 = [k3 0 -k3 0; 0 0 0 0; -k3 0 k3 0; 0 0 0 0];
[m,n] = size(M2);
M2_new = zeros(m+2,n+2);
M2_new(1:m,1:n) = M2;
disp(M2);
1 0 -1 0 0 0 0 0 -1 0 1 0 0 0 0 0
disp(M2_new);
1 0 -1 0 0 0 0 0 0 0 0 0 -1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

More Answers (1)

M1=eye(4); % simply symmetric matrix to play with
N=2; % number columns/rows to insert
R=2;C=2; % starting row, column at which to insert
Z=zeros(size(M1,1),N); % zeros columns to insert; could be anything constant
M2=[M1(:,1:C) Z M1(:,C+1:end)]; % step 1; insert the columns
M2=[M2(1:R,:); [Z.' zeros(N)]; M2(R+1:end,:)]; % step 2; insert rows; must augment the Z to match new
The latter is quite simple to just place the original in the corner of a larger -- but there is a MATLAB syntax "trick" -- start with M1 again, then--
S=size(M1); S=S+N; % get size vector, augment to desired size
M2=M1; % start with original
M2(S(1),S(2))=0; % set outer bound value; ML automagically zero extends

Categories

Find more on Operators and Elementary Operations in Help Center and File Exchange

Tags

Asked:

on 15 Mar 2022

Answered:

dpb
on 15 Mar 2022

Community Treasure Hunt

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

Start Hunting!