How to conditionally delete columns in a cell array
1 次查看(过去 30 天)
显示 更早的评论
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,
0 个评论
采纳的回答
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)
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.
.
更多回答(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))
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!