Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic formatting of strings in Matlab

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.

like image 898
Shantanu Avatar asked Oct 06 '22 14:10

Shantanu


1 Answers

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.

like image 87
PearsonArtPhoto Avatar answered Oct 10 '22 03:10

PearsonArtPhoto