fprintf cell array if its size changes

1 view (last 30 days)
Akbar
Akbar on 4 May 2018
Answered: dpb on 4 May 2018
I want my cell Array to appear in matlab file. But the Array size may Change from time to time and I have to Change the number of "%s" in "fprintf". In the provided code I have 5 "%s" Statements. Later I might Need 7 or 10 etc. Is there an automatic way so that I dont have to adjust manually every time? The number of "%s" should depend on length of the cell Array.
myCellArray = {'t','x', 'k1',k2,'k3'};
fprintf(myFile, 'function dX = myFunction(%s,%s,%s,%s,%s)\n',myCellArray{:})
Result is like this, where the number of arguments may change:
function dX = myFunction(t,x,k1,k2,k3)

Accepted Answer

dpb
dpb on 4 May 2018
Sure...just build dynamic format string...
>> fmt=['function dX = myFunction(' repmat('%s,',1,length(myCellArray)-1) '%s)\n']
fmt =
'function dX = myFunction(%s,%s,%s,%s,%s)\n'
>> fprintf(fmt,myCellArray{:})
function dX = myFunction(t,x,k1,k2,k3)
>>

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!