Shantanu
Shantanu

Reputation: 53

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.

Upvotes: 5

Views: 957

Answers (2)

PearsonArtPhoto
PearsonArtPhoto

Reputation: 39698

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.

Upvotes: 2

HericDenis
HericDenis

Reputation: 1425

Try sprintf function, here is the documentation. Than you do something like:

sprintf('something %[flag][width].[precision][conversion] %...', arg1, ...)

for integer decimals you can just do:

sprintf('%d', integer)

Upvotes: 2

Related Questions