フィルターのクリア

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 ビュー (過去 30 日間)
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 件のコメント
Rik
Rik 2019 年 12 月 19 日
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 2019 年 12 月 19 日
編集済み: Naagy Omar 2019 年 12 月 19 日
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

サインインしてコメントする。

採用された回答

Chuguang Pan
Chuguang Pan 2019 年 12 月 19 日
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 件のコメント
Naagy Omar
Naagy Omar 2019 年 12 月 19 日
Hello!
It still gives me error in line 2. I can't figure out why?
Naagy Omar
Naagy Omar 2019 年 12 月 19 日
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

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by