我想根据第二个条目对行进行排序,即按第二列排序。第二列的每个条目都是一个数组字符(表示一个时间戳)。也可能有缺失值,即第二列中的条目可以是[]。我该怎么做呢?
发布于 2011-08-09 18:56:11
如果要排序的矩阵是A,则需要使用sortrows()函数,然后使用
sorted_matrix = sortrows(A,2);
发布于 2011-08-09 18:59:27
我首先使用函数DATENUM将时间戳从字符串转换为数字值。然后,您需要用占位符替换空单元格的内容,如NaN
。您可以使用函数SORTROWS根据第二列进行排序。下面是一个示例:
>> mat = {1 '1/1/10' 3; 4 [] 6; 7 '1/1/09' 9} %# Sample cell array
mat =
[1] '1/1/10' [3]
[4] [] [6]
[7] '1/1/09' [9]
>> validIndex = ~cellfun('isempty',mat(:,2)); %# Find non-empty indices
>> mat(validIndex,2) = num2cell(datenum(mat(validIndex,2))); %# Convert dates
>> mat(~validIndex,2) = {NaN}; %# Replace empty cells with NaN
>> mat = sortrows(mat,2) %# Sort based on the second column
mat =
[7] [733774] [9]
[1] [734139] [3]
[4] [ NaN] [6]
在这种情况下,NaN
值将排序到底部。
https://stackoverflow.com/questions/7001294
复制相似问题