Add an element if string meets conditions

8 ビュー (過去 30 日間)
Karen Landeros
Karen Landeros 2020 年 8 月 26 日
コメント済み: Star Strider 2020 年 8 月 26 日
A = ["tennis", "pizza", "switch", "popcorn", "laptop", "cupboard"];
word = "lookie"
for i=1:length(A)
if xxxx
str = append(A,word)
end
end
My desired result would be for every word that starts with a 'p', append "lookie".
so the output would be
[tennis pizzalookie switch popcornlookie laptop cupboard]
How can I do this would a loop? I tried using startWith but when I set the condition, lookie is appended to all the words not just the ones I want.

回答 (1 件)

Star Strider
Star Strider 2020 年 8 月 26 日
編集済み: Star Strider 2020 年 8 月 26 日
This seems to be homework, however it’s nevertheless an interesting problem.
Try this:
A = ["tennis", "pizza", "switch", "popcorn", "laptop", "cupboard"];
word = "lookie";
Idx = startsWith(A, "p");
Out = A;
Out(Idx) = append(A(Idx),word)
producing:
Out =
1×6 string array
"tennis" "pizzalookie" "switch" "popcornlookie" "laptop" "cupboard"
This requires R2019b or later.
EDIT — Corrected typographical error.
  2 件のコメント
Karen Landeros
Karen Landeros 2020 年 8 月 26 日
Thank you so much! Don't worry it's not homework. Just a question I had since I make up random problems for myself to help me since coding in general is not my forte (yet? :0).
Star Strider
Star Strider 2020 年 8 月 26 日
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.

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

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by