How to vectorize writing to a txt file

3 次查看(过去 30 天)
Hi there,
I have to write a function in matlab to create a txt file with the following format:
(x(1),y(1)),(x(2),y(2)),...(x(end),y(end))
I have the following piece of code (whre L is the length of vectors x and y)
for r=1:L;fprintf(fileOutput,['(',num2str(time(r)),',',num2str(signal(r)),'), ']);end
which obviously does the trick but I was wondering if anybody knows how to vectorize the expresion so that it runs much faster.
Any help will be welcomed!!
Thank you!

采纳的回答

Cedric
Cedric 2013-4-24
编辑:Cedric 2013-4-24
You could go for something like this:
buffer = sprintf('(%f,%f),', [time; signal]) ; % FormatSpec repeated.
buffer(end) = [] ; % Remove extra ','.
fid = fopen('output.txt', 'w') ;
fwrite(fid, buffer) ;
fclose(fid) ;

更多回答(1 个)

esbolico
esbolico 2013-4-24
Dear Cedric,
thank you very much for you solution. Certainly it is a very clever solution and my program now runs hundreds of times faster. I did not even now the sprintf function, thank you for introducing it to me!
Regards
  1 个评论
Cedric
Cedric 2013-4-24
Dear Esbolico,
The interesting "thing" with SPRINTF and FPRINTF, is that they will repeat the format (here '(%f,%f),') as many time as needed to print all elements of the array(s) that are given to them. It is certainly useful when you want to avoid writing loops. I'm glad it helped!
Regards

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by