Search code examples
matlabmatrixmatrix-indexingsubmatrix

Extracting every n-th column from matrix


I need to extract every n-th column from my matrix.

For example I have a matrix:

A =
     1    23    34    53    67    45    67    45
    12    34    45    56    67    87    98    12
     1     2     3    45    56    76    87    56

And I want to extract each group of three columns, i.e. deleting every fourth. My data should be like:

X =
     1    23    34    67    45    67
    12    34    45    67    87    98
     1     2     3    56    76    87

So I would skip the 4th column, then the 8th column and so on. I know how to extract every n-th column and row but I couldn't figure out how to use that to get what I need.


Solution

  • If you want to "save" every fourth column, then the syntax would be:

    toKeep = 4:4:8;
    A = rand(3,8) % Insert your matrix
    B = A(:,toKeep);
    

    i.e. you assign those values to a new matrix. In your case, you want to remove them, thus you can simply assign an empty matrix to those places, which practically deletes them.

    toRemove = 4:4:8; %Every fourth column
    A = rand(3,8) % Insert your matrix
    A(:,toRemove) = [];
    

    EDIT 1

    As Wolfie correctly notes in the comments, you can improve this a bit by writing toRemove together with A(:,toRemove) and using the end keyword such that you have:

    A = rand(3,8) % Insert your matrix
    A(:,4:4:end) = [];
    

    In this case, you do not have to worry about the size of the matrix.

    EDIT 2:

    This approach will of course also work, for general cases without a period. The variable toRemove will just have to contain the indexes of the columns to remove, e.g.

    toRemove = randperm(8,randi(5)); %Select up to 5 random columns to remove
    A = rand(3,8) % Insert your matrix
    A(:,toRemove) = [];
    

    PS. If you want to keep the original matrix, A you can just assign it to B=A; first and then perform the operation on B instead.