create vector based on string data

1 次查看(过去 30 天)
cell_array = {
'FA.EA';
'FA.EB';
'FA.EC';
'FA.EA';
'FA.EB';
'FB.EC';
'FB.EA';
'FB.EB';
'FC.EC';
'FC.ED';
'FC.EA';
'FC.EB'}
Based on the above cell_array i wanted to create 2 vectors.
vector1 = [1 1 1 1 1 2 2 2 3 3 3 3]; % based on the first 2 characters FA FB and FC
The 3 categories can increase. It must work for any data (FA FB FC FD FE FF...)
vector2 = [1 2 3 1 2 3 1 2 3 4 1 2]; % based on the charcters EA EB EC ED

采纳的回答

KSSV
KSSV 2019-3-12
编辑:KSSV 2019-3-12
S = {
'FA.EA';
'FA.EB';
'FA.EC';
'FA.EA';
'FA.EB';
'FB.EC';
'FB.EA';
'FB.EB';
'FC.EC';
'FC.ED';
'FC.EA';
'FC.EB'}
v1 = cellfun(@(x) x(1:2),S,'un',0) ;
[c,ia,v1] = unique(v1) ;
v1
v2 = cellfun(@(x) x(4:5),S,'un',0) ;
[c,ia,v2] = unique(v2) ;
v2

更多回答(1 个)

Guillaume
Guillaume 2019-3-12
I would do it like this:
cell_array = {
'FA.EA';
'FA.EB';
'FA.EC';
'FA.EA';
'FA.EB';
'FB.EC';
'FB.EA';
'FB.EB';
'FC.EC';
'FC.ED';
'FC.EA';
'FC.EB'}
splitted = regexp(cell_array, '([^.]+)\.(.+)', 'tokens', 'once'); %split at the .
splitted = vertcat(splitted{:});
[~, ~, vector1] = unique(splitted(:, 1))
[~, ~, vector2] = unique(splitted(:, 2))

类别

Help CenterFile Exchange 中查找有关 Tables 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by