create vector based on string data

1 Ansicht (letzte 30 Tage)
Elysi Cochin
Elysi Cochin am 12 Mär. 2019
Beantwortet: Guillaume am 12 Mär. 2019
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

Akzeptierte Antwort

KSSV
KSSV am 12 Mär. 2019
Bearbeitet: KSSV am 12 Mär. 2019
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

Weitere Antworten (1)

Guillaume
Guillaume am 12 Mär. 2019
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))

Kategorien

Mehr zu Tables finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by