How to conditionally delete columns in a cell array

4 Ansichten (letzte 30 Tage)
Blue
Blue am 29 Apr. 2020
Kommentiert: Star Strider am 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,

Akzeptierte Antwort

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

Weitere Antworten (1)

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

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by