MATLAB Answers

0

adding headers when using fprintf to write to text

Danielle Leblance さんによって質問されました 2016 年 12 月 30 日
最新アクティビティ Image Analyst
さんによって コメントされました 2016 年 12 月 31 日
Hi,
I am writing a matrix to text using the following codes:
fid = fopen('Datav1Call_1993.txt','w+');
for idx = 1:size(DataPaper,1)
line = DataPaper(idx,~isnan(DataPaper(idx,:))); % creates the line of data without NaNs
fprintf(fid,[repmat('%d ',1,length(line)),'\n'],line);
end
fclose(fid);
how can i add headers to the columns?

  1 件のコメント

Write 'em before the loop after you open the file...result will likely be more satisfactory for looking at if you use widths on the field specifications to line things up...

サインイン to comment.

タグ

1 件の回答

Image Analyst
Answer by Image Analyst
on 30 Dec 2016
 Accepted Answer

For example, after fopen() and before the loop:
if fid == -1
errorMessage = sprintf('Error opening Datav1Call_1993.txt')
uiwait(errordlg(errorMessage));
return; % Bail out
end
% Now write header string.
fprintf(fid, 'header 1 header 2 header 3 whatever \n');

  6 件のコメント

thanks that was very helpful
>> ['first',
'second',
'last']
Error using vertcat
Dimensions of matrices being concatenated are not consistent.
>>
Yes, the triple dots are needed Danielle. With them it's like ['first', 'second', 'last'] which equals 'firstsecondlast', a single 1-d character array. Without them it tries to make a 2D array and for that to succeed, all strings need to be the same length because you can't have a 2-D array with a ragged right edge. However this demo works:
s1 = ['first', ...
'second', ...
'last']
s2 = ['first-',
'second',
'last--']
You get
s1 =
firstsecondlast
s2 =
first-
second
last--
Note you get a 1-D character array for the first and a 2-D array for the second. I padded the strings so that all strings had 6 characters so now it can make a 3 by 6 character array.

サインイン to comment.



Translated by