如何在没有循环的情况下使用均匀增加的元素制作矩阵

时间:2017-09-28 11:53:28

标签: matlab

 0     0     1     1
 1     1     2     2
 2     2     3     3
 3     3     4     4
 4     4     5     5

我想在没有for循环的情况下制作上面的矩阵。 我只知道如何用循环来做。 这是我的代码

x = [0 0 1 1];
for i = 1:4   
    x= [x;x(1,:)+i]
end

在函数':'中有一种方法吗?或者以其他方式。 我想知道如何在没有循环的情况下将增加的元素值插入矩阵行。

4 个答案:

答案 0 :(得分:3)

您可以使用bsxfun

result = bsxfun(@plus,x,(0:4).')

在Matlab 2016b或更新版本中,您还可以直接扩展单例维度:

result = x + (0:4).'

答案 1 :(得分:1)

您还可以使用cumsum累计对列进行求和。因此,创建您的起始向量,其下面的行矩阵为其他行。

cumsum([0 0 1 1; ones(4,4)]) % ones(n-1, 4) for result with n rows, input 4 columns

这具有能够轻松完成其他步长的优点

cumsum([0 0 1 1; 2*ones(4,4)]) % steps of 2

此外,如果我们使用repmat

,它可以处理每列中的不同间隔
% Row one ↓   interval per col ↓   
cumsum([0 0 1 1; repmat([1 2 3 4], 4, 1)]); % Again, use n-1 in place of 4

答案 2 :(得分:0)

如果你垂直连接你想要的行向量然后进行转置,你将得到所需的结果(在这个例子中是x=[0:4;0:4;1:5;1:5]')。

答案 3 :(得分:0)

您可以使用kron +建议的方法之一here

kron(hankel(0:4,4:5),[1 1])