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 次查看(过去 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
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 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