37. categorical数组和talbe数组
37.1 categorical数组
icecream_cell = {'a','b','c','d','e','f'}; % {'a'} {'b'} {'c'} {'d'} {'e'} {'f'}
icecream_cat = categorical(icecream_cell); % 把数组中的每个元素转化为整数
A = [3,2;3,3;2,1;2,2;3,2];
valueset = [1:3];
catnames = {'child','adult','senior'};
B = categorical(A,valueset,catnames,'Ordinal',true); % 'Ordinal',true: 代表排序关系
% 5×2 categorical 数组
% senior adult
% senior senior
% adult child
% adult adult
% senior adult
B(1,1) > B(1,2); % logical 1
37.2 talbe数组
names = {'a','b','c'};
weights = [120;125;130];
heights = [178;180;182];
patients = table(weights,heights,'RowNames',names); % 行名字不能重复,列名字不能重复
% 3×2 table
% weights heights
% a 120 178
% b 125 180
% c 130 182
patients(1:2,1); % 选择第1和2行,第1列表格元素
% weights
% a 120
% b 125
patients('a',:); % 选择‘a'所在行
% weights heights
% a 120 178
patients(:,'heights'); % 选择heights所在列
patients({'a','b'},:); % 选择’a'和'b'所在行
summary(patients);
% weights: 3×1 double
% Values:
% Min 120
% Median 125
% Max 130
% heights: 3×1 double
% Values:
% Min 178
% Median 180
% Max 182
patients{:,'weights'};
% ans =
% 120
% 125
% 130
[~,i_order] = sort(patients{:,'weights'}); % 根据weights进行排序,记录排序后元素的之前位置
% i_order =
% 1
% 2
% 3
patients(i_order,:); % 根据i_order位置顺序进行交换
38. sort排序
vec = [85 70 100 95 80 91];
sort(vec,'descend'); % 降序,100 95 91 85 80 70
sort(vec,'ascend'); % 升序,70 80 85 91 95 100
[sort_as,sort_weizhi] = sort(vec);
% sort_as = 70 80 85 91 95 100,记录排序后结果
% sort_weizhi = 2 5 1 6 4 3,记录元素排序前的位置
vec([2 5 1 6 4 3]); % 通过交换元素位置进行排序,70 80 85 91 95 100