Reorder cell array based on unique string value

2 次查看(过去 30 天)
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 !

采纳的回答

Clayton Gotberg
Clayton Gotberg 2021-4-19
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 个评论
Ben
Ben 2021-4-20
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 !

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by