problem using regexprep and fprintf at the same time
1 view (last 30 days)
Show older comments
Hi everybody!
I have a problem.. I want to print in a txt file my matrix newmat_fin in which i have replaced 0 with blank spaces, using this function:
regexprep(evalc('newmat_fin'), '0', '')
and to print:
fid=fopen('voxels.txt','w'); fprintf(fid, '%6.0f %6.4f\r\n', newmat_fin); fclose(fid);
Why if I display the matrix in the command window there are the blank spaces while in my txt file there are still the zeros??
Can anyone help me please? Thank you very much in advance!!
Sara
0 Comments
Accepted Answer
Adam
on 20 Nov 2014
regexprep doesn't work by reference, you have to assign the output back to your matrix
0 Comments
More Answers (1)
Guillaume
on 20 Nov 2014
Your fundamental issue is that functions in matlab never change what you pass as input. regexprep doesn't modify its input, it returns the modification as output. Therefore, you need to do:
newexpr = regexprep(...);
That won't make your code work, however, for several reasons:
Your fprintf assumes a matrix of numbers (double), whereas regexprep returns strings (char)
You can't have numbers mixed with characters in a matrix, therefore you can't have a matrix of doubles with blank spaces.
Your regexprep will replace any 0 by an empty character.For example the number 10 will become '1'
Possibly this would work for you:
newmat_as_char = num2str(newmat_fin); %don't use eval or evalc for that!
newmat_as_char_with_no_0 = regexprep(newmat_as_char, '\<0+\>', ' ');
fprintf(fid, '%s\n\r', newmat_as_char_with_no_0); %if you open the file as 'wt', you don't need to bother about the '\r'
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!