How to convert string to numeric variable in if statement
이전 댓글 표시
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.
채택된 답변
추가 답변 (2개)
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
Ot
2014년 3월 5일
Chandrasekhar
2014년 3월 5일
the variables C1,C2 etc should contain some values for eg: C1 =1; C2 = 2; etc
what do C1, C2 represent in your script?
Chandrasekhar
2014년 3월 5일
Ok..can you explain the logic clearly
what does the array team contain? and what exactly you want to find?
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
Giorgos Papakonstantinou
2014년 3월 5일
편집: Giorgos Papakonstantinou
2014년 3월 5일
OR maybe:
I made a fake Team
A=randi(4, 1,801);
Team=cell(1,801);
for ii=1:length(A)
if A(ii)==1
Team{ii}='B1';
elseif A(ii)==2
Team{ii}='B2';
elseif A(ii)==3
Team{ii}='C1';
else
Team{ii}='C2';
end
end
You do maybe this:
[~,B] = ismember(Team, {'B1' 'B2' 'C1' 'C2'})
Ot
2014년 3월 5일
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.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!