Removing empty cells from cell array with multiple rows while preserving the rows
조회 수: 17 (최근 30일)
이전 댓글 표시
I have cell array of string values with empty cells in some of in the middle of some of the rows. I would like to delete the empty cells and shift the cells to the left but I don't want any shifting to happen in between rows. I tried the code below but it returns cell array of cell arrays. How can I modified the code so it returns a cell array of string values like the orginal array but only the empty cells removed?
compacted_instances = {};
for i = 1:size(instance_array_nolateral, 1)
% Get the current row
current_row = instance_array_nolateral(i,:);
current_row = {current_row};
% Remove empty cells from the current row
compacted_row = current_row(~cellfun('isempty', current_row));
% Store the compacted row in the new cell array
compacted_instances{i} = compacted_row;
end
댓글 수: 2
James Tursa
2024년 5월 9일
편집: James Tursa
2024년 5월 9일
A cell array is a rectangular array by definition. You can shift things around (e.g., move stuff to the left to overwirte empty cells and move the empty cells to the right end), but you still have to have a rectangular array as a result. It is not entirely clear what your desired result should be. A cell array of string arrays, with each string array a different number of elements? Or ...? Could you post a small example of input and desired output?
채택된 답변
Voss
2024년 5월 9일
C = { ...
'Right knee','Head','Elbow/forearm',[]; ...
'Hand/wrist',[],'Pelvis',[]; ...
[],[],'Ankle/foot',[]; ...
[],'Left knee',[],'Shoulder'; ...
}
Here's one way to move the empty cells to the right:
[~,cols] = sort(cellfun(@isempty,C),2);
[m,n] = size(C);
rows = repmat((1:m).',1,n);
C = C(sub2ind([m,n],rows,cols))
And if you then want to remove columns that contain only empty cells:
C(:,all(cellfun(@isempty,C),1)) = []
댓글 수: 2
Voss
2024년 5월 10일
편집: Voss
2024년 5월 10일
You're welcome!
The idea is: first do cellfun(@isempty,C) to get a matrix of logical (true/false) values the same size as C saying whether each cell of C is empty. Then sort(_,2) sorts each row of that logical matrix; since false (0) is less than true (1), the order is for the non-empty ones to go before the empty ones. The second output (cols) from sort() tells you which column the elements of C need to go to. Then the rows variable is just 1:m repeated for each column, since each element should stay in its own row. Finally, convert those row and column indices into linear indices using sub2ind(), and rearrange C using those linear indices to get the final result.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
