5

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the suggestion. But I'm trying to get this done while writing the output into a file. So I guess the display statement would not work, right?
I've come up with an alternative that works, but is a bit harder to explain. To output it to a file, just add the fid as the first argument, and you're set.
Okay, I think I have the answer to what I was looking for. Basically I was unsure if an entire array could be passed to the sprintf/fprintf statement. Turns out, Matlab does permit it. Wait, did you edit your response to include the thing about the array? Yes, that's what I've been looking for. Thanks a ton! :)
Yeah, I'd upvoted your response, though I wasn't aware of accepting. Thanks again.
2

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)

2 Comments

The usage of disp and sprintf together is redundant; using the latter is sufficient, says Matlab.
@H.Muster, updated my answer, some time no use MatLab forgot that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.