I'm trying to write a Matlab program that takes an input from the user for the number of rows to be displayed and accordingly prints something like :
1
2 2
3 3 3
.. so on
Now I could get this output using two for loops, but is it possible to do the same with one for loop? Specifically, I'd like to know if there's a way by which we could pass the iteration value of the for loop to the sprintf/fprintf statement to format the string in a way similar to '%3d' so that the sprintf/fprintf statement knows how many variables are to be printed on each line. Hope that wasn't too messy.
Thank you!
Shantanu.
You could simply create an array each pass through to the appropriate size, like this:
fid=1; % Will print out to the stdout, but can replace this with the folder to write to
for x=1:3
stuff=zeros(x,1)+x;
fprintf(fid,'%s ',stuff)
fprintf(fid,'\n');
end
Note that if an array is passed to a fprintf
statement, it will simply repeat it until the array is finished.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With