Updating variable after each loop iteration

16 ビュー (過去 30 日間)
Dinh Phuc Nguyen
Dinh Phuc Nguyen 2022 年 4 月 25 日
コメント済み: Dinh Phuc Nguyen 2022 年 4 月 25 日
Hello everyone, I am almost new in matlab. I am trying to update my variable according to user's input. I want every letter I entered match with the generated_word, the letter will earse; in such way that promt(1)='m' will give newChr(1)='atlabcounity'; promt(2)='a' will give newChr(2)=tlbcounity'; promt(3)='t' will give newChr(3)='lbcouniy' and so on.
Here is the code that I have tried to run but its not working in my favor:
generated_word='matlabcommunity'
promt=[]:
newChr=[];
for i=1:length(generated_word)
promt(i)=input("Enter: ",'s');
% delete the correct input's letters from the generated word
newChr=erase(generated_word,promt(i));
disp(newChr)
if promt == 'x'
break
end
end
disp(newChr)

採用された回答

Walter Roberson
Walter Roberson 2022 年 4 月 25 日
generated_word='matlabcommunity'
promt = strings(0):
newChr=[];
for i=1:length(generated_word)
promt(i)=input("Enter: ",'s');
if promt(i) == 'x'
break
end
% delete the correct input's letters from the generated word
newChr=erase(generated_word,promt(i));
disp(newChr)
generated_word = newChr;
end
disp(newChr)
Caution: your code has a bug for the case where the input word contains the same letter multiple times.
  2 件のコメント
Walter Roberson
Walter Roberson 2022 年 4 月 25 日
generated_word='matlabcommunity'
generated_word = 'matlabcommunity'
erase(generated_word, 'm')
ans = 'atlabcounity'
Notice that "erase" removes all occurances of the same letter. If you want to remove only the first occurence then either you should use a different function, or else you should arrange so that the bit to be erased matches only one place, by carefully generating a patternarray() such as by using anchors. You might want to reconsider using erase(). For example
regexprep(generated_word, 'm', '', 'once')
ans = 'atlabcommunity'
Dinh Phuc Nguyen
Dinh Phuc Nguyen 2022 年 4 月 25 日
Thank you for your help!!! I'm very much appreciate this!!

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

その他の回答 (1 件)

KSSV
KSSV 2022 年 4 月 25 日
generated_word='matlabcommunity' ;
newChr=[];
promt = cell(length(generated_word),1) ;
for i=1:length(generated_word)
promt{i}=input("Enter: ",'s');
% delete the correct input's letters from the generated word
newChr=erase(generated_word,promt{i});
disp(newChr)
if strcmp(promt{i},'x')
break
end
end
disp(newChr)
  1 件のコメント
Dinh Phuc Nguyen
Dinh Phuc Nguyen 2022 年 4 月 25 日
Thank you for answearing my question, but the code is not really updated the genereated_word every iteration like promt(1)='m' will give newChr(1)='atlabcounity'; promt(2)='a' will give newChr(2)=tlbcounity'

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by