Matrix to be printed to a text file

조회 수: 5 (최근 30일)
Ionut  Anghel
Ionut Anghel 2015년 6월 23일
편집: Stephen23 2015년 6월 23일
Hi, I have the following matrix AA=[Nan 1 2 3 Nan 4 5 6 Nan 7 8 9 Nan 10 Nan Nan] I want to print this matrix to a file: myfile.txt the code looks like:
fid01 = fopen('mynewfile.txt', 'w'); fprintf(fid01, '%9.8E %9.8E %9.8E %9.8E\n', transpose(AA)); fclose('all');
As one can see, one has to use transpose function in order to print correct the matrix in myfile.txt. But because of Nan the following error occurs:
"Invalid file identifier. Use fopen to generate a valid file identifier." How can avoid this. I have to use NaN in my matrix in order to replace with blanks so in myfile.txt I should have
'' 1 2 3
'' 4 5 6
'' 7 8 9
'' 10 '' ''
The file will be huge [210000x4] ~ 20 MB.
Thank you
  댓글 수: 2
Stephen23
Stephen23 2015년 6월 23일
편집: Stephen23 2015년 6월 23일
There should be no problem with writing NaN's to text file:
AA = [NaN,1,2,3;NaN,4,5,6;NaN,7,8,9;NaN,10,NaN,NaN];
fid = fopen('temp.txt','wt');
fprintf(fid,'%9.8E %9.8E %9.8E %9.8E\n',AA.');
fclose(fid);
And the generated text file:
NaN 1.00000000E+00 2.00000000E+00 3.00000000E+00
NaN 4.00000000E+00 5.00000000E+00 6.00000000E+00
NaN 7.00000000E+00 8.00000000E+00 9.00000000E+00
NaN 1.00000000E+01 NaN NaN
Can you please show the exact code that you are using?
Ionut  Anghel
Ionut Anghel 2015년 6월 23일
Your answer works well My code is: AA=[Nan 1 2 3; Nan 4 5 6; Nan 7 8 9; Nan 10 Nan Nan]; fid01 = fopen('mynewfile.txt', 'w'); fprintf(fid01, '%9.8E %9.8E %9.8E %9.8E\n', transpose(AA)); fclose('all');
I dont't know what was wrong since if will have a number instead of NaN is working. The tricky question is now how can I replace NaN with blanks in the matrix and printed to mynewfile.txt. Thank you.
P.S. I want to accept your answer but because you put write it in the comments section does not work.

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2015년 6월 23일
편집: Stephen23 2015년 6월 23일
The problem are your NaN's, which you wrote as Nan, not NaN. Character case is important in MATLAB! Here with Nan:
>> AA = [Nan 1 2 3; Nan 4 5 6; Nan 7 8 9; Nan 10 Nan Nan];
Undefined function or variable 'Nan'.
With correct NaN, no error:
>> AA = [NaN 1 2 3; NaN 4 5 6; NaN 7 8 9; NaN 10 NaN NaN];

추가 답변 (1개)

Ingrid
Ingrid 2015년 6월 23일
the error that is given has nothing to do with the NaNs in your file but means that the file to were you want to write could not have been opened correctly. This would show as fid01 == -1
are you sure that you have writing permissions to were you want to write the file?
  댓글 수: 1
Ionut  Anghel
Ionut Anghel 2015년 6월 23일
Yes, I have permission. I'm creating this file. If I replace NaN with 0 or any other number is working very well.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by