Help with for loop and fprintf

9 views (last 30 days)
aurc89
aurc89 on 19 Jan 2015
Commented: Image Analyst on 19 Jan 2015
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

Answers (2)

Image Analyst
Image Analyst on 19 Jan 2015
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 Comments
aurc89
aurc89 on 19 Jan 2015
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.
Image Analyst
Image Analyst on 19 Jan 2015
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

Sign in to comment.


Guillaume
Guillaume on 19 Jan 2015
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]);

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!