Reorder cell array based on unique string value
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 !
0 commentaires
Réponse acceptée
Clayton Gotberg
le 19 Avr 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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Characters and Strings dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!