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)
Show older comments
Mads Albertsen
on 11 Aug 2021
Commented: Mads Albertsen
on 11 Aug 2021
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
0 Comments
Accepted Answer
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
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)
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.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!