How to sort a cell array with respect to another cell array?
4 views (last 30 days)
Show older comments
Hello:
If I have cell array A:
cellA = {'A', 'B', 'C', 'D'; 1, 2, 3, 4; 5, 6, 7, 8; 9, 1, 2, 3}
and cell array B:
cellB = {'C', 'A', 'D'; 1, 2, 3; 4, 5, 6; 7, 8, 9}
Is there a way to sort cellB with respect to cellA (specifically the first row, but with the capability to look to other rows to tiebreak)? Such that the final cellB array looks something like this, including the null spaces:
cellBFinal = {'A' '' 'C' 'D'; 2 [] 1 3; 5 [] 4 6; 8 [] 7 9}
Thank you!
0 Comments
Accepted Answer
Dyuman Joshi
on 27 Jun 2023
Here's one approach -
%Note that this approaches requires the 1st row of cellA to be sorted
cellA = {'A', 'B', 'C', 'D'; 1, 2, 3, 4; 5, 6, 7, 8; 9, 1, 2, 3};
cellB = {'C', 'A', 'D'; 1, 2, 3; 4, 5, 6; 7, 8, 9};
%positions of elements of row 1 from cellB which are common to elements of row 1 from cellA
[~,y]=ismember(cellA(1,:),cellB(1,:))
z = any(y==0);
if z
%Concatenate empty spaces according to the class of elements with cellB
%only there is a missing common element (in this case 'B')
cellB = [cellfun(@(x) x([]), cellB(:,1), 'uni', 0) cellB];
end
%Final output
cellC = cellB(:,y+z)
More Answers (1)
Jon
on 27 Jun 2023
cellA = {'A', 'B', 'C', 'D'; 1, 2, 3, 4; 5, 6, 7, 8; 9, 1, 2, 3}
cellB = {'C', 'A', 'D'; 1, 2, 3; 4, 5, 6; 7, 8, 9}
[lia,lib] = ismember(cellA(1,:),cellB(1,:))
cellBFinal = cell(size(cellA,2),size(cellB,1))
cellBFinal(:,lia) = cellB(:,lib(lia))
See Also
Categories
Find more on Operators and Elementary Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!