write a matrix to a text file
1 次查看(过去 30 天)
显示 更早的评论
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 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
thanks!
1 个评论
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
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 个评论
Walter Roberson
2011-6-22
The [] are horizontal concatenation in this contexts. Building up a string by parts.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!