MATLAB: Formatting or encoding issue using fprintf

charconversionencodingfclosefopenformatformattingfprintfMATLABregexprepreplace

Hi everyone. I am writing a script that is intended to automatically update information for me but I am having trouble towards the end where the string is saved to a .txt file.
The code that I have so far is:
S=regexprep('base string','keyword','new word')
G=char(S)
M=fopen('file.txt','wt')
fprintf(M,'%s',G)
fclose(M)
I am using regexprep to alter the original file and replace a word within. However, trying to use fprintf directly from the regexprep gives me the error "function is not defined for 'cell' inputs"
To avoid this error, I used the char function to convert the cell S into a character array. However, when G (the result of the char function) is saved to a text file, it is clearly formatted incorrectly. [An excerpt of the saved file: "b('-t'*(a('-t'*(eeoo"]
I can not seem to find any other functions that either do not produce an error in the fprintf function or give me gibberish in my saved file.
Any help would be greatly appreciated. Thanks for reading this long post at the least!
~Sarah 🙂

Best Answer

fprintf(M,'%s',S{:}) %without needing to convert to char()
Or,
fprintf(M,'%s',G.')