使用嵌套for循环生成数字表

时间:2015-04-11 10:44:37

标签: matlab for-loop matrix

我尝试编写一个打印此输出的函数:

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

我写了这段代码,但是我没有得到所需的输出:

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

如何更正此算法或者您能告诉我,是否还有其他方法可以解决此问题?

1 个答案:

答案 0 :(得分:2)

我不知道" print" 的含义,但这是你可以开始的方式:

%// 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]

要将其打印到文件,您可以使用。

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

你得到:

enter image description here

仅适用于命令窗口:

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

就足够了。如果您不喜欢'\t',请选择所需的分隔符。


如果你坚持使用嵌套for循环,你可以这样做:

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

显示:

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