Reorganizing cell array according to column
조회 수: 7 (최근 30일)
이전 댓글 표시
I have a cell-array 40x6, the values in the 6th column are the numbers 1 and 2 which correspond to two different conditions in my study. The rows of the cell array are currently organized in a way that all of the 2 conditions rows are first and then all of the 1 condition rows.
This is a short excerpt of what the 6th column looks like now.
[2 2 2 2 2 1 1 1 1 1]
I want to re-sort this column so that I create a column with the condtions alternating [1 2 1 2 1 2], and then sort the rows according to this new order. Is there a way to do this with the sort function?
댓글 수: 4
채택된 답변
Stephen23
2019년 2월 26일
편집: Stephen23
2019년 2월 26일
>> data
data =
[1x33 char] [ 0] [11.7701] [17.9263] [2] [2]
[1x33 char] [ 5.5659] [ 0] [ 0] [1] [2]
[1x33 char] [ 0] [ 7.2146] [22.2491] [2] [2]
[1x33 char] [13.1006] [ 0] [ 0] [1] [2]
... lots of lines here
[1x32 char] [25.7023] [ 0] [ 0] [1] [1]
[1x32 char] [ 0] [15.9568] [19.7365] [2] [1]
[1x32 char] [12.9951] [ 0] [ 0] [1] [1]
[1x32 char] [ 0] [ 8.5696] [21.2321] [2] [1]
[1x32 char] [10.4371] [ 0] [ 0] [1] [1]
>> [~,idx] = sort([data{:,6}]);
>> idx([1:2:end,2:2:end]) = idx;
>> new = data(idx,:)
new =
[1x32 char] [ 0] [ 6.4649] [26.5270] [2] [1]
[1x33 char] [ 0] [11.7701] [17.9263] [2] [2]
[1x32 char] [16.2326] [ 0] [ 0] [1] [1]
[1x33 char] [ 5.5659] [ 0] [ 0] [1] [2]
[1x32 char] [ 0] [15.1299] [24.5024] [2] [1]
... lots of lines here
[1x32 char] [12.9951] [ 0] [ 0] [1] [1]
[1x34 char] [22.2777] [ 0] [ 0] [1] [2]
[1x32 char] [ 0] [ 8.5696] [21.2321] [2] [1]
[1x34 char] [ 0] [ 7.6076] [23.7789] [2] [2]
[1x32 char] [10.4371] [ 0] [ 0] [1] [1]
[1x34 char] [16.6640] [ 0] [ 0] [1] [2]
댓글 수: 2
추가 답변 (1개)
Mani Teja
2019년 2월 26일
Hello Danna,
The below code can be used if you are looking for other ways apart from using the "Sort" function:
% Converting from cell to mat format
C = cell2mat(Place_Your_Cell_Array_Here);
% Use this matrix to visualize the changes made to the original matrix
Compare_C = C;
% Divide the given matrix into half matrices (Based on 1s and 2s in 6th Column)
D_1 = C(1:1:20,:);
D_2 = C(21:1:40,:);
% Sorting of C Matrix
for i = 1:2:40
C(i,:) = D_2((i+1)/2,:);
C(i+1,:) = D_1((i+1)/2,:);
end
% Converting from mat to cell format
Your_Sorted_Cell_Array = num2cell(C);
% Alternatively the matrix can be sorted by identifying 1s and 2s in 6th
% Column using if loops and a counter for a particular order
Hope this helps !
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Time Series Events에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!