How to recursively add symbol in a for loop?

2 views (last 30 days)
Hi everyone,
I have this code (the following is a simplified version to give the idea):
Rnum = 12;
Nnum = 34;
First={1};
Second={1};
for i=15:Nnum
iS=mat2str(i);
for n=1:Rnum
nS=mat2str(n);
First{end+1,1}=char({['mytext1 ', iS, 'mypath', nS, 'mytext2 ']});
Second{end+1,1}=char({['mytext1 ', iS, 'mypath', nS, 'mytext2 ',]});
end
end
The output is a 241x1 cell array in which the first cell is always 1 and the other cells are containing characters (like: mytext1 15mypath1mytext2 ). What I would like to do is to add, for each iteration of the loops, the symbol ">" in a recursive way in order to obtain:
  • mytext1 15mypath1mytext2 > (for the second cell of the "First" cell array);
  • mytext1 15mypath2mytext2 >> (for the third cell of the "First" cell array);
  • mytext1 15mypath3mytext2 >>> (for the fourth cell of the "First" cell array);
And, of course, exactly the same for the "Second" cell array (starting with >, then >>, then >>>, etc.). This, for all the 241 lines, not only for the inner loop. Any ideas on how to reach this goal?
Thanks a lot,
Gabriele

Accepted Answer

dpb
dpb on 4 Apr 2020
Don't try to catenate all with text operators; use sprintf (or possibly some of the new string class functionality that includes BASIC-like + operators and the like)--
Basic idea/example--clearly the above specific strings won't be what you're actually wanting to reproduce and one presumes that probably the mypath and mytext placeholders are actually variables instead of actual text, but following should give the idea:
>> n=1;
>> sprintf(['mytext1 %dmypath%dmytext2 ' repmat('>',1,n)],1,15)
ans =
'mytext1 1mypath15mytext2 >'
>> n=2;
>> sprintf(['mytext1 %dmypath%dmytext2 ' repmat('>',1,n)],1,15)
ans =
'mytext1 1mypath15mytext2 >>'
>>
Instead of burying all the text for the format string in the call to sprintf, also build a format string dynamically outside:
fmt1=repmat('%s %d',1,i);
will build the number of repeats of the 'string n' pattern needed for the given loop index number, i

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!