Odd behavior when using character sequence as an array index
6 次查看(过去 30 天)
显示 更早的评论
I was trying to show my students how to use a vector as a lookup table to swap the case of alphabetic characters when I encountered this behavior that I do not understand.
Here is the lookup table:
>> swapCase = char(1:127)
ans =
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
Now in that string I want to replace the upper case letters with lower case letters:
>> swapCase('A':'Z') = 'a':'z';
But it shows this error:
In an assignment A(:) = B, the number of elements in A and B must be the same.
Hm? I didn't type swapCase(:) , I typed swapCase('A':'Z') . This looks like a bug of some sort. Either the Matlab parser is wrong or the error message is wrong.
It works fine if the argument is the numeric sequence 65:90 or the explicit string 'ABC...Z' . The only way I could get it to work with a character sequence is by placing it in square brackets:
>> swapCase(['A':'Z']) = 'a':'z';
But then that contradicts Matlab's principle of vector concatenation. What I mean is that 'A':'Z' and ['A':'Z'] and [['A':'Z']] should yield the same vector/string 'ABC...Z', but this is a situation where it does not.
0 个评论
回答(1 个)
Philip Borghesani
2013-11-19
character indexing is a bit dangerous because of it and this which is not a bug just a special case:
a=1:5;
>> a(':')=-1
a =
-1 -1 -1 -1 -1
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!