problem using regexprep and fprintf at the same time

2 ビュー (過去 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'
  1 件のコメント
Sara
Sara 2014 年 11 月 20 日
Thank you very much!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeExternal Language Interfaces についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by