Home > front end >  write two matlab vectors in a file and insert backslash between the vectors
write two matlab vectors in a file and insert backslash between the vectors

Time:02-01

Given

a=[1 2 3];
b=[4 5 6];
Output in file should look like:
1 2 3 / 4 5 6

Is there a way to achieve this in one single fprintf() call?

I have a solution where there is no backslash between a and b

fprintf(fileID, '%d %d ', a, b);
output:
1 2 3 4 5 6 (no backslash in between)

CodePudding user response:

You can get a single call to fprintf if you’re willing to construct your format string dynamically.

fileID=1;
a=[1,2,3];
b=[4,5,6,7];
c=[8,9];

fprintf(fileID,strjoin(cellfun(@(c)sprintf('%d ',c),{a,b,c},'UniformOutput',false),'/ '));

It’s not pretty, and it’s probably only worth the trouble if you’ve got a lot of calls to fprintf in a loop and need to avoid overhead, but technically it achieves what you asked for.

  • Related