How to Print a Numerical Vector to a List?
12 views (last 30 days)
Show older comments
Hello,
I have an array with multiple vectors each with thousands of numbers and I want to print each of these vectors to a list of strings, each with a specific format and with a maximum of 8 numbers per list.
For example:
I have a vector temp = [1 2 3 4 5 6 7 8 9 10 11 12 13]
I want to print this vector to two strings like this
str1 = '+,1,2,3,4,5,6,7,8,'
str2 = '+,9,10,11,12,13,'
It would be useful to save each string to a separate entry on an array because later these strings will be printed to a .txt file.
I have tried to do this but I always have trouble with the last line that may not have the desired 8 elements..
Does anyone know a clean way to do this?
Here are some printscreens to try to clarify:
The red rectangle is my reference ID
The green rectangle is the matrix with the numbers I want to print
The blue column is the vector of numbers I want to print (This is inside the previous green rectangle)
And finally, this is how the printed file will look like
Can anyone help me?
Thank you very much!
0 Comments
Accepted Answer
dpb
on 15 Sep 2018
Edited: dpb
on 16 Sep 2018
fmt=[' +,' repmat('%d,',1,8)]; % format w/ extra blank each line for delimiter later
str=split(sprintf(fmt,vec),' '); % write to string, break into substrings at delimiter
str(1)=[]; % eliminate first empty record/string
>> str
str =
2×1 cell array
{'+,1,2,3,4,5,6,7,8,'}
{'+,9,10,11,12,13,' }
>>
ADDENDUM
Put delimiter at end of record instead--
fmt=['+,' repmat('%d,',1,8) ' '];
>> split(sprintf(fmt,tmp),' ')
ans =
2×1 cell array
{'+,1,2,3,4,5,6,7,8,'}
{'+,9,10,11,12,13,' }
>>
More Answers (0)
See Also
Categories
Find more on Characters and Strings 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!