sorting cell arrays based on nested cell array?
조회 수: 2 (최근 30일)
이전 댓글 표시
I have a 5x5 cell array and the last cell column is nested cell array which contains double and I have to sort the whole cell array based on the double? is there way to do it?
댓글 수: 2
Jan
2021년 3월 17일
An explicit example of the input data would be useful. Are the elements of the last column all scalar cells?
Data = {1, 2, {3}; ...
4, 5, {6}};
If so, why do you use a nested cell for the last column?
채택된 답변
Jan
2021년 3월 17일
편집: Jan
2021년 3월 17일
score = {'Name', 'Score', 'Rating'; ...
'Messi', {{97}}, {[9.75]}; ...
'Ronaldo', {98}, {[9.8]}; ...
'Neymar', {{{{96}}}}, {[9.7]} };
This is your example in a more readable format. This is a really strange format. The best idea is to fix the code, which produces these data. The nesting of the cells is a shot in you knee.
If the code, which produces this, is not yours and you cannot improve it, cleanup the data at first:
function C = cleanMyCell(C)
for iC = 1:numel(C)
aC = C{iC};
while iscell(aC)
aC = aC{1};
end
C{iC} = aC;
end
end
After score=cleanMyCell(score) your data look like:
score = {'Name', 'Score', 'Rating'; ...
'Messi', 97, 9.75; ...
'Ronaldo', 98, 9.8; ...
'Neymar', 96, 9.7};
Now the sorting is easy:
Rating = [score{2:end, 3}];
[~, SortIndex] = sort(Rating);
score(2:end, :) = score(SortIndex + 1, :)
추가 답변 (1개)
Purushothaman K
2021년 3월 17일
I assume that you are trying to sort a cell array based on last column which is again a cell array whose first (and only element) cell value is double.
I believe there may be no inbuilt function which can do this directly. But we can use sortrows function by making some changes to the input cell array.
Using sortrows(cellarray, column) we can sort the given cell array based on a column. But the column should not be a cell array.
Check below link for more information about sortrows function
Let’s take an example of below input cell array
x = {2,2,2,2,{2};1,1,1,1,{1};4,4,4,4,{4};5,5,5,5,{5};3,3,3,3,{3}}
Steps to solve the issue
- Convert the 5th column to numeric
numCol = cellfun(@cell2mat, x(:,5))
2. Modify input array with converted column
x(:,5) = num2cell(numCol)
3. Sort the cell array
sortrows(x,5)
Note: This solution modifies the input cell array as it converts the cell array to cell value.
참고 항목
카테고리
Help Center 및 File Exchange에서 Cell Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!