I want to make a loop that keeps replacing its own 'S's with SLSRSLS any N number of times

1 回表示 (過去 30 日間)
i want it like this, but in a loop
N = 3;
k = ('S');
k_1 = regexprep(k,{'S'},{'SLSRSLS'});
k_2 = regexprep(k_1,{'S'},{'SLSRSLS'});
k_3 = regexprep(k_2,{'S'},{'SLSRSLS'});
k_4 = regexprep(k_3,{'S'},{'SLSRSLS'});
disp(k_1)
I dont know if there is a easier way to do it, from what i have researched, changing variable names in a loop is not fun

採用された回答

Simon Chan
Simon Chan 2021 年 8 月 11 日
N = 3;
k{1} = {'S'};
for r = 1:N
k{r+1} = strrep(k{r},{'S'},{'SLSRSLS'})
end
Results are k{1}, k{2}, k{3} & k{4}.
k{4} is
{'SLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSLSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSLSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLS'}
  4 件のコメント
Stephen23
Stephen23 2021 年 8 月 11 日
編集済み: Stephen23 2021 年 8 月 11 日
@Mads Albertsen: you get that error message because variable k already exists in the workspace and Simon Chan's code is not robustly written to handle that. Try this instead:
N = 5;
k = {'S'};
for ii = 2:N
k{ii} = regexprep(k{ii-1},'S','SLSRSLS');
end
celldisp(k)
k{1} = S k{2} = SLSRSLS k{3} = SLSRSLSLSLSRSLSRSLSRSLSLSLSRSLS k{4} = SLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSLSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSLSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLS k{5} = SLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSLSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSLSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSLSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSLSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSLSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSLSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSLSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSLSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSLSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLSLSLSRSLSLSLSRSLSRSLSRSLSLSLSRSLS
If you do not need to store all of those strings (i.e. you only need the last one) then get rid of the cell array entirely.
Mads Albertsen
Mads Albertsen 2021 年 8 月 11 日
only needed the last one, so makig k {1} to just k did the trick. but i am curius, if i want to do it with multiple strings and charachters at the same time without them overlapping can it be done in strrep?

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by