0

I try to write a function in which print this output:

1
2 4
3 6 9
4 8 12 16
5 10 15 20 25

I wrote this code, but I'm not getting the desired output:

rows = 5;
% there are 5 rows
for i=1:rows
    for j=1:i
        b=i*j;
    end
    fprintf('%d\n',b)
end

How to I need to correct this algorithm or can you tell me, if there are any other alternate methods to solve this?

1
  • 1
    Use proper indention and you will notice the obvious error. Your inner loop is not printing anything. Commented Apr 11, 2015 at 11:14

1 Answer 1

2

I don't know what you mean by "print", but this is how you could start:

%// initial vector
a = 1:5;

A = tril( bsxfun(@plus,a(:)*[0:numel(a)-1],a(:)) )
%// or 
A = tril(a.'*a)   %'// thanks to Daniel!
mask = A == 0
out = num2cell( A );
out(mask) = {[]}

A =

     1     0     0     0     0
     2     4     0     0     0
     3     6     9     0     0
     4     8    12    16     0
     5    10    15    20    25

out = 

    [1]      []      []      []      []
    [2]    [ 4]      []      []      []
    [3]    [ 6]    [ 9]      []      []
    [4]    [ 8]    [12]    [16]      []
    [5]    [10]    [15]    [20]    [25]

To print it to a file, you can use.

out = out.'; %'
fid = fopen('output.txt','w')
fprintf(fid,[repmat('%d \t',1,n) '\r\n'],out{:})
fclose(fid)

and you get:

enter image description here

just for the command window:

out = out.'; %'
fprintf([repmat('%d \t',1,n) '\r\n'],out{:})

will be sufficient. Choose your desired delimiter, if you don't like '\t'.


If you insist on a nested for loop, you can do it like this:

rows = 5;
% there are 5 rows
for ii = 1:rows
    for jj = 1:ii
        b = ii*jj;
        if ii <= jj
           fprintf('%d \n',b)
        else
           fprintf('%d ',b)
        end
    end  
end

displays:

1 
2 4 
3 6 9 
4 8 12 16 
5 10 15 20 25 
Sign up to request clarification or add additional context in comments.

4 Comments

No need for bsxfun here, A=tril(a'*a)
@Daniel Thanks for the hint, included!
Thanks thewaywewalk for assistance .. the above mentioned algorithm includes some function with which i am not familiar ... i want to make a script which will create the above mentioned table .... I want to make this script with using nested for loop only... kindly assist me in nested for loop only... thanks
thank you so much @thewaywewalk for the correct assistance..... :) it absolutely work

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.