'Generate matrix using matlab built-in function [duplicate]

I want generate matrix of the form:

1 2 3
2 3 4
3 4 5

using MATLAB. I can make code to generate matrix above:

for i=1:3
    for j=1:3
        idx(i,j)=i+j-1;
    end
end

But, I want use MATLAB built-in function to generate matrix above to simplify my code (I don't want using looping again). Anyone know MATLAB built-in function to generate matrix above?



Solution 1:[1]

In MATLABĀ® R2016b and later:

[1:3] + [0:2]'

Old style:

bsxfun(@plus,1:3,[0:2]')

Solution 2:[2]

Try using

[1:3; 2:4; 3:5]

This generates a 3 x 3 matrix and simplifies your code down to one line.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stewie Griffin
Solution 2 Dolimight