How to insert a zero column vector in a matrix according to a particular position?
14 views (last 30 days)
Show older comments
I have a matrix 4*4. i want to insert a zero column vector based on a particular position. position can be 1 or 2 or 3 or 4 or 5. How can we implement this?
0 Comments
Answers (3)
dpb
on 13 Jun 2022
Edited: dpb
on 14 Jun 2022
ixInsert=N; % set the index
Z=zeros(size(M,1)); % the insert vector (don't hardcode magic numbers into code)
if ixInsert==1 % insert new column in front
M=[Z M];
elseif ixInsert==(size(M,2)+1) % or at end
M=[M Z];
else % somewhere in the middle
M=[M(:,1:ixInsert-1) Z M(:,ixInsert:end)];
end
Add error checking to heart's content...
Ayush Singh
on 14 Jun 2022
Hi chan,
From your statement I understand that you want to insert a zero column vector at a given position in a 4*4 matrix.
Now suppose you have a N*N matrix and you want to insert the zero column vector at nth position For that
Create a N*1 zero column vector first.
zero_column_vector=zeros(4,1) % to create N row and 1 column zero vector (Here N is 4)
Now that you have your zero column vector you would need the position where you want to place the vector in the matrix.
Lets say the position is 'n'. So now concatenate the zero column vector in the given position by
[A(:,1:n) zero_column_vector A(:,n+1:end)] % A is the N*N matrix here
2 Comments
dpb
on 15 Jun 2022
Exactly what my solution above does except I chose to insert before the input column number instead of after -- that's simply a "count adjust by one" difference.
Star Strider
on 16 Jun 2022
Edited: Star Strider
on 17 Jun 2022
Another approach —
M = randn(4) % Original Matrix
[rows,cols] = size(M);
A = zeros(rows,cols+1); % Augmented Matrix
zeroCol = 3; % Insert Zero Column At #3
idx = setdiff(1:size(A,2), zeroCol);
A(:,idx) = M
A = zeros(rows,cols+1);
zeroCol = 5; % Insert Zero Column At #5
idx = setdiff(1:size(A,2), zeroCol)
A(:,idx) = M
EDIT — (17 Jun 2022 at 10:59)
This can easily be coded to a function —
M = randn(4)
for k = 1:size(M,2)+1
fprintf(repmat('—',1,50))
InsertZerosColumn = k
Result = InsertZeroCol(M,k)
end
function NewMtx = InsertZeroCol(OldMtx, InsertZerosCol)
[rows,cols] = size(OldMtx); % Get 'OldMtx' Information
NewMtx = zeros(rows,cols+1); % Augmented Matrix
idx = setdiff(1:cols+1, InsertZerosCol); % 'NewMtx' Column Index Vector
NewMtx(:,idx) = OldMtx; % New Matrix With Inserted Zeros Column
end
.
0 Comments
See Also
Categories
Find more on Multidimensional Arrays 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!