Reorder cell array based on unique string value
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Clayton Gotberg
il 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
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Characters and Strings in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!