Home > database >  Deleting consecutive and non-consecutive columns from a cell array in Matlab
Deleting consecutive and non-consecutive columns from a cell array in Matlab

Time:10-18

I'm trying to delete multiple consecutive and non-consecutive columns from a 80-column, 1-row cell array mycells. My question is: what's the correct indexing of a vector of columns in Matlab?

What I tried to do is: mycells(1,[4:6,8,9]) = [] in an attempt to remove columns 4 to 6, column 8 and 9. But I get the error: A null assignment can have only one non-colon index.

CodePudding user response:

Use a colon for the first index. That way only the 2nd index is "non-colon". E.g.,

mycells(:,[4:6,8,9]) = []

MATLAB could have been smart enough to recognize that when there is only one row the 1 and : amount to the same thing and you will still get a rectangular array result, but it isn't.

CodePudding user response:

Before getting the above VERY VERY HELPFUL AND MUCH SIMPLER answers, I ended up doing something more convoluted. As it worked in my case, I'll post it here for anyone in future:

  1. So, I had a cell array vector, of which I wanted to drop specific cells. I created another cell array of the ones I wanted to remove:

remcols = mycells(1,[4:6,8,9])

  1. Then I used the bellow function to overwrite onto mycells only those cells which are different between remcols and mycells (these were actually the cells I wanted to keep from mycells):

mycells = setdiff(mycells,remcols)

This is not neat at all but hopefully serves the purpose of someone somewhere in the world.

  • Related