How to conditionally delete columns in a cell array

4 views (last 30 days)
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,

Accepted Answer

Star Strider
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.
.

More Answers (1)

Guillaume
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))

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!