MATLAB Answers

0

How to Print a Numerical Vector to a List?

Asked by Gonçalo Pimenta on 14 Sep 2018
Latest activity Edited by dpb
on 16 Sep 2018
Accepted Answer by dpb
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

Sign in to comment.

1 Answer

Answer by dpb
on 15 Sep 2018
Edited by dpb
on 16 Sep 2018
 Accepted Answer

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,' }
>>

  2 Comments

It's perfect dpb!
Thank you very much!
Actually, can be made "even more perfect"!
Use
fmt=['+,' repmat('%d,',1,8) ' '];
to place the delimiter at the end of each record and won't get the empty first record and thus can eliminate the need to strip it from the result...

Sign in to comment.