computing vectors with string and numbers (easy question)

조회 수: 2 (최근 30일)
Andrea Miceli
Andrea Miceli 2021년 3월 25일
편집: Paul Hoffrichter 2021년 3월 26일
Hi evreyone,
I have a vector of names(str vector) and i would like to associate a number to each name
For example evreytime that the name 'Andrea' came up in the first vectror in the second one it gives me back the number 3.
Thank you for your time!
  댓글 수: 2
Stephen23
Stephen23 2021년 3월 25일
"I have a vector of 12 names(str vector) and i would like to associate a number to each name (so from 1:12)."
That just sounds like the indices.
Andrea Miceli
Andrea Miceli 2021년 3월 25일
I modifed the question, now it should be clearer.

댓글을 달려면 로그인하십시오.

채택된 답변

Paul Hoffrichter
Paul Hoffrichter 2021년 3월 26일
편집: Paul Hoffrichter 2021년 3월 26일
Here is code that keeps the indexing scheme based upon the order in which the names occur in your vector of strings.
>> S = ["Howard" "Howard" "joe" "april" "andrea" "joe" "andrea" "Howard"]
S =
1×8 string array
"Howard" "Howard" "joe" "april" "andrea" "joe" "andrea" "Howard"
>> SUniq = unique(S, 'stable')
SUniq =
1×4 string array
"Howard" "joe" "april" "andrea"
>> [~, Locb] = ismember(S, SUniq)
Locb =
1 1 2 3 4 2 4 1

추가 답변 (1개)

Paul Hoffrichter
Paul Hoffrichter 2021년 3월 25일
편집: Paul Hoffrichter 2021년 3월 25일
>> S = ["joe" "april" "andrea" "joe" "andrea"]
S =
1×5 string array
"joe" "april" "andrea" "joe" "andrea"
>> SU = unique(S)
SU =
1×3 string array
"andrea" "april" "joe"
>> [~,Locb] = ismember(S, SU)
Locb =
3 2 1 3 1
Every time "joe" came up in S, it shows up as a 3 in Locb.
Every time "andrea" came up in S, it shows up as a 1 in Locb.
Every time "april" came up in S (only 1 time), it shows up as a 2 in Locb.

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by