How to convert string to numeric variable in if statement

2 ビュー (過去 30 日間)
Ot
Ot 2014 年 3 月 5 日
I want to covert my string variable into numeric variables.
I have got string Variable Team that shows which players are in. For example C2, C1, B2, B1 etc.
I want to give each player a numeric value which represents the team.
I tried the following
for i =1:length(Team)
if Team(i) strcmp 'C1'
Team(i) = 1
elseif Team(i) strcmp 'C2'
Team(i) = 2
end
end
but get the error:
??? Conversion to logical from cell is not possible.

採用された回答

Jos (10584)
Jos (10584) 2014 年 3 月 5 日
AllTeams = {'A1','B1','C1','C2','C3'} % all the teams
Team = {'A1','B1','C1','A1','C3','A1','unknown','C1'} % Team{k} is the team of player k is
% map team names to numbers
[~,TeamNumber] = ismember(Team, AllTeams)
X = find(TeamNumber <= 2) % players in team 1 or 2

その他の回答 (2 件)

Chandrasekhar
Chandrasekhar 2014 年 3 月 5 日
for i =1:length(Team)
if Team(i)== str2num(C1)
Team(i) = 1
elseif Team(i)==str2num(C2)
Team(i) = 2
end
end
  5 件のコメント
Chandrasekhar
Chandrasekhar 2014 年 3 月 5 日
Ok..can you explain the logic clearly
what does the array team contain? and what exactly you want to find?
Ot
Ot 2014 年 3 月 5 日
編集済み: Ot 2014 年 3 月 5 日
The array team is an (801X1) cell. The Team cell tells for each of the 801 players in the Database in which team they play. The string values B1, B2, C1 and C2 are the names of the different team.
I want to adress an numeric value to each Team instead of this string value, so that I afterwards can sort the players based on their teams and calulate Mean Sprint times and STD of each Team's sprint times.
I hope it is clear now.

サインインしてコメントする。


Giorgos Papakonstantinou
Giorgos Papakonstantinou 2014 年 3 月 5 日
編集済み: Giorgos Papakonstantinou 2014 年 3 月 5 日
If this is exactly what you want to do then try this:
Team = {'C1' 'C2' 'C3' 'C4'}
for ii=1:length(Team)
switch Team{ii}
case 'C1'
Team{ii} = 1;
case 'C2'
Team{ii} = 2;
case 'C3'
Team{ii} = 3;
case 'C4'
Team{ii}=4
otherwise
fprintf('hallo')
end
end
But you change the variable Team... Maybe you assign the numbering to a new variable.
  3 件のコメント
Ot
Ot 2014 年 3 月 5 日
This works, but then my variable Team is still considered as an cell while I want to transfer it into an double.
maybe with str2num? but I don't know how?
Giorgos Papakonstantinou
Giorgos Papakonstantinou 2014 年 3 月 5 日
cell2mat(Team)
But in this way you alter the variable Team. Why don't you try this:
[~,B] = ismember(Team, {'B1' 'B2' 'C1' 'C2'})
It will have the same effect. You will not alter the cell Team. Instead you create a new variable B which is the same with the one you asked for.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeData Preprocessing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by