# How to conditionally delete columns in a cell array

7 views (last 30 days)
Blue on 29 Apr 2020
Commented: Star Strider on 29 Apr 2020
Hi,
I have a simple cell array that look like this:
input = {'A','B','A','A','A','A','A','A'; 'A','A','B','A','A','A','A','A'; 'A','A','A','A','A','A','A','A'}
What I want to do is to simply delete all the columns that dont contains 'B' but only those to the right hand side of the last column that contains a 'B'.
In other words the ouput would look like this:
ouput = {'A','B','A'; 'A','A','B'; 'A','A','A'}
How would I do that ?
Thank you,

Star Strider on 29 Apr 2020
Try this:
inputc = {'A','B','A','A','A','A','A','A'; 'A','A','B','A','A','A','A','A'; 'A','A','A','A','A','A','A','A'};
isB = cell2mat(cellfun(@(x)ismember('B',x), inputc, 'Uni',0));
[r,c] = find(isB, 1, 'last');
outputc = inputc(:,1:c)
producing:
outputc =
3×3 cell array
{'A'} {'B'} {'A'}
{'A'} {'A'} {'B'}
{'A'} {'A'} {'A'}
I could have combined ‘isB’ and the find call in one line, however breaking it into two lines is easier to understand.
.
##### 2 CommentsShowHide 1 older comment
Star Strider on 29 Apr 2020
As always, my pleasure!

Guillaume on 29 Apr 2020
If your cell array is indeed a cell array of single characters, then you'd be better off storing it as a char matrix:
input = cell2mat(input);
In which case:
[~, lastc] = max(input == 'B', [], 2);
output = input(:, 1:max(lastc))