fprintf problem, can't print
정보
이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.
이전 댓글 표시
My code is as follow:
for i = 1:length(Ta)
fprintf(fid, '%s;%.2f;%.2f;%.2f;%.2f\n', DateTimeStr(i), Ta(i), Pa(i), Tb(i), Pb(i));
end
DateTimeStr(i) is an string array of 14 characters. Ta(i), Pa(i), Tb(i), Pb(i)) are floating number.
Somehow in my text file DateTimeStr(i) only print 1 character, the rest is OK. Here is how it print to file:
2;55.05;87.82;54.26;84.27
2;55.04;87.80;54.26;84.27
2;55.07;87.81;54.26;84.28
2;55.04;87.81;54.25;84.28
2;55.03;87.81;54.25;84.28
it should be like this
20120906093000;55.04;87.80;54.26;84.27
20120906093100;55.07;87.81;54.26;84.28
20120906093200;55.04;87.81;54.25;84.28
20120906093300;55.03;87.81;54.25;84.28
댓글 수: 1
What exactly is "a string array of 14 characters"? Obviously "DateTimeStr(i)" causes the problem, so please post exactly the type and size of this variable as well as its contents.
In my test it works as expected:
D = ["12345678901234", "12345678901234"]
fprintf('%s;\n' D(1));
So please explain the difference of this simple example and your data.
답변 (1개)
Star Strider
2018년 4월 16일
Since ‘DateTimeStr’ is likely an character array, you have to address it as such in the variable reference to it:
fprintf(fid, '%s;%.2f;%.2f;%.2f;%.2f\n', DateTimeStr(i,:), Ta(i), Pa(i), Tb(i), Pb(i));
댓글 수: 5
Jan
2018년 4월 16일
+1. Good guess.
Star Strider
2018년 4월 16일
@Jan — Thank you!
@Stephen — The reference to ‘DateTimeStr(i)’ defaults to ‘DateTimeStr(i,1)’, so only the first ‘2’ prints.
Testing that with:
DateTimeStr = ['20120906093000'
'20120906093100'
'20120906093200'
'20120906093300'];
A = [55.04,87.80,54.26,84.27
55.07,87.81,54.26,84.28
55.04,87.81,54.25,84.28
55.03,87.81,54.25,84.28];
Ta = A(:,1);
Pa = A(:,2);
Tb = A(:,3);
Pb = A(:,4);
fid = 1;
for i = 1:length(Ta)
fprintf(fid, '%s;%.2f;%.2f;%.2f;%.2f\n', DateTimeStr(i,:), Ta(i), Pa(i), Tb(i), Pb(i));
end
produces:
20120906093000;55.04;87.80;54.26;84.27
20120906093100;55.07;87.81;54.26;84.28
20120906093200;55.04;87.81;54.25;84.28
20120906093300;55.03;87.81;54.25;84.28
as desired.
I suspect Jan’s test worked because he used string variables, and my code assumes a character array.
Star Strider
2018년 4월 16일
It confused me too at first.
I experimented by printing it first with a single subscript, (printing only a 2), then adding the second subscript and printing the entire character vector. That’s when I figured out that ‘DateTimeStr’ is an array of character vectors, since only that assumption will produce the observed results.
이 질문은 마감되었습니다.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!