Reorder cell array based on unique string value

3 Ansichten (letzte 30 Tage)
Ben
Ben am 19 Apr. 2021
Kommentiert: Ben am 20 Apr. 2021
Dear Matlab users,
I'm stuck in my code and a help will be very much appreciated.
I have a 23×6 cell array containing string (it can be longer and larger)
Testmat = {'A' 'B' '' '' '' '';'A' 'B' '' '' '' '';'A' 'B' '' '' '' '';'A' 'B' '' '' '' '';'A' 'B' '' '' '' '';'A' 'B' '' '' '' '';'A' 'B' 'C' 'D' 'E' 'F';'A' 'B' 'C' 'D' 'E' 'F';'A' 'B' 'C' 'D' 'E' 'F';'A' 'B' 'C' 'D' 'E' 'F';'A' 'B' 'C' 'D' 'E' 'F';'A' 'B' 'C' 'D' 'E' 'F';'A' 'B' 'C' 'D' 'E' 'F';'B' 'C' 'E' '' '' '';'B' 'C' 'E' '' '' '';'B' 'C' 'E' '' '' '';'B' 'C' 'E' '' '' '';'B' 'C' 'E' '' '' '';'B' 'C' 'E' '' '' '';'B' 'C' 'E' '' '' '';'C' 'D' '' '' '' '';'C' 'D' '' '' '' '';'C' 'D' '' '' '' ''}
Each string variable are in positions 1:size(Testmat,2) (followed by empty cells if numel(unique(Testmat(:,1)))<size(Testmat,2) )
Each string variable (A, B, C, etc..) are associated (in the same position) to a {300x1 double} cell in another 23×6 cell array (doublemat).
Do you have a elegant way to reorder/sort Testmat to have a unique variable (A,B,C etc..) in each column and get their location (to reorder doublemat as well?). At the end I would like to have all the 'A' in column 1, 'B' in column 2 etc with a corresponding matrix containing all locations.
Something like this:
'A' 'B' '' '' '' ''
...
'A' 'B' '' '' '' ''
'A' 'B' 'C' 'D' 'E' 'F'
...
'A' 'B' 'C' 'D' 'E' 'F'
'' 'B' 'C' '' 'E' ''
...
'' 'B' 'C' '' 'E' ''
'' '' 'C' 'D' '' ''
'' '' 'C' 'D' '' ''
Thank you in advance for your help !

Akzeptierte Antwort

Clayton Gotberg
Clayton Gotberg am 19 Apr. 2021
If you want to find which of the rows of your string array contain specific values, you can use this:
% This can also be generated by finding the unique characters in Testmat
fieldNames = {'A', 'B', 'C', 'D', 'E', 'F'};
for i = 1:size(fieldNames,2) % For each value in fieldNames
nameExists = any(strcmp(Testmat(:,:),fieldNames{i})')'; % Mark that value as present if
% it appears anywhere in the row
resultingMatrix(:,i) = char(nameExists.*double(fieldNames{i})); % Make a char matrix with
% fieldNames{i} where it appears and spaces otherwise.
end
  1 Kommentar
Ben
Ben am 20 Apr. 2021
Thank you very much !!
I was far from the solution !
And it also works if numel(fieldNames) > size(Testmat,2) so thank you again very much !

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Produkte


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by