write a matrix to a text file

조회 수: 1 (최근 30일)
Arash
Arash 2011년 6월 22일
I'd like to write a matrix into a text file, but I don't want elements with NaN value appear in the file, instead I want an empty space for each NaN value, here is a part of the matrix:
  1. 1 NaN NaN NaN NaN
  2. 3 4 4 NaN NaN
  3. 6 1 NaN NaN NaN
  4. 2 2 NaN NaN NaN
  5. 4 4 5 NaN NaN
  6. 6 2 3 2 NaN
thanks!
  댓글 수: 1
Walter Roberson
Walter Roberson 2011년 6월 22일
Are the NaN certain to be at the end of the line? If not then a different method would have to be used.

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

채택된 답변

Laura Proctor
Laura Proctor 2011년 6월 22일
I wrote the following code which writes it line by line. Do you need the line breaks to be as they are in the original matrix? If not, then a FOR loop wouldn't be necessary.
A = [ 1 NaN NaN NaN NaN
3 4 4 NaN NaN
6 1 NaN NaN NaN
2 2 NaN NaN NaN
4 4 5 NaN NaN
6 2 3 2 NaN ]
fid = fopen('stuff.txt','w+');
for idx = 1:size(A,1)
line = A(idx,~isnan(A(idx,:))); % creates the line of data without NaNs
fprintf(fid,[repmat('%d ',1,length(line)),'\n'],line);
end
fclose(fid);
  댓글 수: 2
Arash
Arash 2011년 6월 22일
thanks! could you please explain a little bit about "[" on the line: fprintf(fid,[repmat('%d ',1,length(line)),'\n'],line);
what exactly brackets do?
Walter Roberson
Walter Roberson 2011년 6월 22일
The [] are horizontal concatenation in this contexts. Building up a string by parts.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by