How to vectorize string/char array concatenation with 'newline' characters for fprintf?

조회 수: 23 (최근 30일)
Hi,
I am currently working with huge XML files that are a few hundred thousdand lines long.
When reading in the XML file I use textscan to split store the entire file as a cell array where each cell is a character array of one line from the document, so each index in the cell array corresponds to one line of text in the XML sheet.
This makes performing vectorized operations really easy and overall the manipulation of the files that I need to perform is executed very fast.
However, the one thing I'm not sure how to vectorize is the code that combinds all of the lines into one character array with line breaks inbetween each line. Since I need the output XML to be identical to the input other than the changes I make and I am currently using fprintf, concatenating the line breaks in manually is the only way I've found to make the output correctly formed so far.
It is probably simple, there may even be a specialized function for writing from a cell array like I need to that I am unaware of; though, for now this is how I am performing these last two steps:
% Reprint xml
xmlOutString = '';
for line = 1:length(xmlData)
xmlOutString = [xmlOutString xmlData{line} newline];
end
% Save ini
xmlFile = fopen(xmlPath,'wt');
fprintf(xmlFile,'%s',xmlOutString);
fclose(xmlFile);
which is painfully slow.
Does anyone know a better method?
Thanks for any suggestions.
  댓글 수: 2
Stephen23
Stephen23 2020년 4월 4일
By far the simplest and most efficient solution would be to add the newline to fprintf:
fprintf(xmlFile,'%s\n',...)
Is there a particular reason why that doesn't work?
Christian Heimlich
Christian Heimlich 2020년 4월 4일
I actually didn't know that fprintf could handle vectors like that, and didn't initially fiddle with it when I got the error saying fprintf doesn't work with cell arrays (just had to use {:}). Also I didn't think it would automatically append instead of overwrite.
Even simpler now, thanks.

댓글을 달려면 로그인하십시오.

채택된 답변

per isakson
per isakson 2020년 4월 4일
This statement should do it
xmlOutString = strjoin( xmlData, '\n' );
  댓글 수: 1
Christian Heimlich
Christian Heimlich 2020년 4월 4일
Ah, 'strjoin'. Exactly what I was trying to find.
Worked perfectly and its lightining fast compartively.
Thanks.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by