Filter löschen
Filter löschen

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?!?

1 Ansicht (letzte 30 Tage)
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 Kommentare
Rik
Rik am 19 Dez. 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 am 19 Dez. 2019
Bearbeitet: Naagy Omar am 19 Dez. 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

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Chuguang Pan
Chuguang Pan am 19 Dez. 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 Kommentare
Naagy Omar
Naagy Omar am 19 Dez. 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by