How to conditionally delete columns in a cell array

5 ビュー (過去 30 日間)
Blue 2020 年 4 月 29 日
コメント済み: Star Strider 2020 年 4 月 29 日
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
Star Strider 2020 年 4 月 29 日
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)
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 件のコメント
Star Strider
Star Strider 2020 年 4 月 29 日
As always, my pleasure!


その他の回答 (1 件)

Guillaume 2020 年 4 月 29 日
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))


Community Treasure Hunt

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

Start Hunting!

Translated by