Help with for loop and fprintf
조회 수: 10 (최근 30일)
이전 댓글 표시
Hello everyone! I have this part of my code:
for r = 1 : length(x1)
fprintf(fidtot, '%f %f %f %f\n', x1(r),x2(r),x3(r),x4(r));
end
that writes 4 columns on a .txt file, where x1,x2,x3 and x4 have the same length. Now, I want to write, on the same file, two more columns y1 and y2 of same length each other but different from the one of x1,x2,x3 and x4. I tried like this:
for r = 1 : length(x1)
fprintf(fidtot, '%f %f %f %f\n', x1(r),x2(r),x3(r),x4(r));
end
for s = 1 : length(y1)
fprintf(fidtot,'%f %f\n', y1(s),y2(s));
end
but like this it doesn't work: instead of adding two more columns (and having 6 columns) it writes the two new columns below the first two ones (x1 and x2). How can I solve it? thank you
댓글 수: 0
답변 (2개)
Image Analyst
2015년 1월 19일
Do it all in one loop
for r = 1 : length(x1)
fprintf(fidtot, '%f %f %f %f ', x1(r),x2(r),x3(r),x4(r));
if r <= length(y1)
fprintf(fidtot,'%f %f\n', y1(r),y2(r));
end
end
And don't have the \n in the first fprintf().
댓글 수: 2
Image Analyst
2015년 1월 19일
If the length of the y's is more than the length of the x's, it's an obvious trivial change to make:
for r = 1 : length(y1)
if r <= length(x1)
fprintf(fidtot, '%f %f %f %f ', x1(r),x2(r),x3(r),x4(r));
end
fprintf(fidtot,'%f %f\n', y1(r),y2(r));
end
Guillaume
2015년 1월 19일
Text files are row based, not column based, therefore you need to write all the columns of the same row before moving to the next row. There's no way around it.
In any case, assuming that s is smaller than r, what do you want to do with the remaining rows? Print 0, NaN, or a nothing?
If 0 or NaN, just expand the smaller matrices to the same number of rows as the others:
x = [x1 x2 x3 x4];
y = [y1 y2];
r = length(x);
s = length(y);
maxlength = max(r, s);
x = [x; zeros(maxlength-r, 4)]; %or [x; nan(maxlength-r, 4)];
y = [y; zeros(maxlength-s, 4)]; %or [y; nan(maxlength-r, 4)];
fprintf(fidtot, '%f %f %f %f %f %f\n', [x y]);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!