Reorder cell array based on unique string value

조회 수: 2 (최근 30일)
Ben
Ben 2021년 4월 19일
댓글: Ben 2021년 4월 20일
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