problem using regexprep and fprintf at the same time

조회 수: 3 (최근 30일)
Sara
Sara 2014년 11월 20일
댓글: Sara 2014년 11월 20일
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

채택된 답변

Adam
Adam 2014년 11월 20일
regexprep doesn't work by reference, you have to assign the output back to your matrix

추가 답변 (1개)

Guillaume
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 CenterFile Exchange에서 External Language Interfaces에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by