How to recursively add symbol in a for loop?

조회 수: 2 (최근 30일)
Gabriele Russo
Gabriele Russo 2020년 4월 4일
댓글: Gabriele Russo 2020년 4월 9일
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

채택된 답변

dpb
dpb 2020년 4월 4일
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
  댓글 수: 1
Gabriele Russo
Gabriele Russo 2020년 4월 9일
Thanks a lot, it’s perfectly doing what I need :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by