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

1 Ansicht (letzte 30 Tage)
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

Akzeptierte Antwort

Simon Chan
Simon Chan am 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 Kommentare
Stephen23
Stephen23 am 11 Aug. 2021
Bearbeitet: Stephen23 am 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 am 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?

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by