problem using regexprep and fprintf at the same time
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Adam
2014-11-20
regexprep doesn't work by reference, you have to assign the output back to your matrix
0 个评论
更多回答(1 个)
Guillaume
2014-11-20
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'
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Environment and Settings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!