Reputation: 11
for var=1:length(str)
switch str(var)
case {'A':'C'}
disp('2')
case {'D':'F'}
disp('3')
case {'G':'I'}
disp('4')
case {'J':'L'}
disp('5')
case {'M':'O'}
disp('6')
case {'P' 'R' 'S'}
disp('7')
case {'T':'V'}
disp('8')
case {'W':'Y'}
disp('9')
end
I am using this code in trying to make a statement such as ('1-800-TO-WELLS') become '1-800-86-93557', but the output is "str=1-800-TO-WELLS and 7". Any amount of tips and help is very appreciated. If I haven't provided a valid enough question please leave comments so I can improve.
Upvotes: 1
Views: 232
Reputation: 125874
Troy gives a very clear answer as to why your code isn't working: {'A':'C'}
results in a 1-element cell array {'ABC'}
, but you want to use a 3-element cell array {'A' 'B' 'C'}
since the way the switch
compares case expressions will result in a match if one cell element exactly matches a given character.
As an alternative to using a for
loop and switch
statement, you could also do this using the ismember
function and some indexing:
% Character/number map and test string:
map = ['ABCDEFGHIJKLMNOPRSTUVWXY'; '222333444555666777888999'];
str = '1-800-TO-WELLS';
% Convert test string:
[isInMap, index] = ismember(str, map(1, :));
str(isInMap) = map(2, index(isInMap));
And the result:
str =
1-800-86-93557
Upvotes: 1
Reputation: 8401
For strings, the cases in the switch
block act like calls to strcmp
, so case <caseExpression>
is true if any(strcmp(<caseExpression>,<switchExpression>))
.
This is important because {'P' 'R' 'S'}
and {'P':'S'}
do not generate the same output:
>> {'P' 'R' 'S'}
ans =
'P' 'R' 'S'
>> {'P':'S'}
ans =
'PQRS'
The first is a 1-by-3 cell array with individual characters as the elements' contents; the second is a 1-by-1 cell array with a 1-by-4 character array as the element's content. Performing a strcmp
on the first one will give true if the <switchExpression>
is a letter in the set while the second will only give a true if <switchExpression>
is exactly 'PQRS'
:
>> strcmp({'P' 'R' 'S'},'S')
ans =
0 0 1
>> strcmp({'P':'S'},'S')
ans =
0
>> strcmp({'P':'S'},'P':'S')
ans =
1
So the 7
pops out because its case is the only one that gives true when given a matching character.
As a side note, you may consider using the otherwise
statement to echo non-matching characters:
switch str(var)
.
.
.
otherwise
disp(str(var));
end
Upvotes: 2