Hello. I have to write a function called occurrence that tests whether a character exists in a string. If it is present, display true and the position (index) of the character. If it is not present, return inf. it gives me an error in line 2. help?!?

2 vues (au cours des 30 derniers jours)
function find_letter(L, string)
n= 1:length(L);
not_found = true;
for k = 1:n
if isequal(L(k).letter, string)
fprintf('letter %s is present! It is the %2.0d item\n', L(k).title, k);
not_found = false;
break; % or return
end
end
if not_found; fprintf('letter not present\n')
end
  2 commentaires
Rik
Rik le 19 Déc 2019
How do you call this function? Also, you're generating a vector for your loop twice, and you haven't set the output to inf yet.
Naagy Omar
Naagy Omar le 19 Déc 2019
Modifié(e) : Naagy Omar le 19 Déc 2019
thank you my friend!
Ive edited the code, but it still gives me an error. i tried just clicking "run" but it doesn't work. I also tried calling the function using "find_character('itscoldtoday, o')" but it returns error in line 3.
function find_character(L, string)
not_found = true;
for k = 1:length(L);
if isequal(L(k).character, string)
fprintf('character %s is present! It is the %2.0d item\n', L(k).title, k);
not_found = false;
break; % or return
end
end
if not_found; fprintf('Inf\n')
end
end

Connectez-vous pour commenter.

Réponse acceptée

Chuguang Pan
Chuguang Pan le 19 Déc 2019
function find_letter(L, string)
n= length(L);
not_found = true;
for k = 1:n
if isequal(L(k), string)
fprintf('letter %s is present! It is the %2.0d item\n', L(k), k);
not_found = false;
break; % or return
end
end
if not_found; fprintf('letter not present\n')
end
find_letter('Hello World!','o');
  2 commentaires
Naagy Omar
Naagy Omar le 19 Déc 2019
Hello!
It still gives me error in line 2. I can't figure out why?
Naagy Omar
Naagy Omar le 19 Déc 2019
Thank you for your help! Hey I tried this and it works!
find_letter('itscoldtoday!','y');
function find_letter(L, string)
not_found = true;
for k = 1:strlength(L);
if isequal(L(k), string)
fprintf('letter %s is present! It is the %2.0d item\n', L(k), k);
not_found = false;
break; % or return
end
end
if not_found; fprintf('letter not present\n')
end
end

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by