Help with for loop and fprintf

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

回答(2 个)

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 个评论

Like this it writes the last two columns until the term N, where N is the length of the first four columns; instead, I want to write the last two columns with their whole length.
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

请先登录,再进行评论。

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]);

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

提问:

2015-1-19

Community Treasure Hunt

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

Start Hunting!

Translated by