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

1 view (last 30 days)
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

Accepted Answer

Simon Chan
Simon Chan on 11 Aug 2021
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 Comments
Stephen23
Stephen23 on 11 Aug 2021
Edited: Stephen23 on 11 Aug 2021
@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 on 11 Aug 2021
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?

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!