why do I get error "Unable to use a value of type string as an index.??"

247 visualizaciones (últimos 30 días)
Aminata camara
Aminata camara el 16 de Mzo. de 2021
Comentada: Aminata camara el 17 de Mzo. de 2021
I wrote a code but I keep getting this error:Unable to use a value of type string as an index., how is that?
%Accepts an input character array from the user and determines how
%many times a user-specified character appears within the character array.
%{
Define variables
strA_a-string
check_string- user-specified character
noccur-Number of time charU appears
%}
%Get a character array
strA_a=string(input('Enter a character array: ','s'));
%Get a user-specified character within the character array
check_string=string(input('Enter a specified character to check occurence: ','s'));
%Get the number of count c coours within A
noccur=count(strA_a,check_string);
%Tell the user
fprintf('the letter %c occurs %d times in the string.\n',check_string,noccur)

Respuestas (1)

Walter Roberson
Walter Roberson el 17 de Mzo. de 2021
Editada: Walter Roberson el 17 de Mzo. de 2021
You probably accidentally assigned a value to a variable named count so that count() in your code is an indexing request instead of a function call.
(Or you might have done so in the past and you had not cleared your variables since then.)
Note:
The part of the instructions about accepting an input character array could be interpreted as expecting you to write a function that takes a parameter that is type char and which is not necessarily a character vector -- for example that it might be valid for the user to pass in
M = ['hi there';
'aminata ']
M = 2×8 char array
'hi there' 'aminata '
and that the counts are to be processed for that. If so, then be careful in your code:
MS = string(M)
MS = 2×1 string array
"hi there" "aminata "
count(MS, "t")
ans = 2×1
1 1
Notice the result of string() of a character array is one string entry per row of the character array, and that if you count() on a string array that the result is per string entry, not total.

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by