Reorganizing cell array according to column
7 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Stephen23
on 26 Feb 2019
Edited: Stephen23
on 26 Feb 2019
>> 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 Comments
More Answers (1)
Mani Teja
on 26 Feb 2019
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 Comments
See Also
Categories
Find more on Time Series Events 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!