Odd behavior when using character sequence as an array index

조회 수: 6 (최근 30일)
Jeffrey Meunier
Jeffrey Meunier 2013년 11월 19일
댓글: Jeffrey Meunier 2013년 11월 19일
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.

답변 (1개)

Philip Borghesani
Philip Borghesani 2013년 11월 19일
This is a known bug: Bug 405376
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 CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by