MATLAB: How to insert columns into an existing matrix without deleting existing columns

columnsindexingmatrix

Let's say I have a matrix with dimension (8×10). I also have an index vector (index_excl) with dim(1×11).
matrix = rand(10,8)
index_excl =
1×11 logical array
0 0 1 0 0 0 0 1 0 0 1
Now I would like to insert a cloumn of zeros (zeros(10,1)) at each of the columns indicated in the index vector. That means in the matrix the third column should be all zeros but it should not delete the existing column. The new matrix would then be of dimension (10,11).
I tried the following:
matrix(:,index_excl) = zeros(10,1)
Assignment has fewer non-singleton rhs dimensions than non-singleton subscripts
Does anybody have an idea how to manage this?

Best Answer

Try this:
matrix = rand(10,8);
index_excl = [0 0 1 0 0 0 0 1 0 0 1] > 0;
AddCols = nnz(index_excl);
new_matrix = zeros(size(matrix,1), size(matrix,2)+AddCols);
new_matrix(:, ~index_excl) = matrix;
The code creates ‘new_matrix’ as a zeros array of the desired size, then writes the columns of the original ‘matrix’ array to the ones you want to add.