How to create a meshgrid padded with a triangle of zeros in the upper-right and lower-left corners

4 次查看(过去 30 天)
I want to take a vector, and turn it into a matrix where the original vector appears in each column, but offset down by the column number, so that I end up with an upper and lower triangle of zeros. For example, if I start with the vector
>> a=1:7
a =
1 2 3 4 5 6 7
I can turn this into a 7x4 matrix where a appears in each column by using the function meshgrid:
>> [~,b]=meshgrid(1:4,a)
b =
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 6 6 6
7 7 7 7
But what I really want is for b to look like this:
b =
1 0 0 0
2 1 0 0
3 2 1 0
4 3 2 1
5 4 3 2
6 5 4 3
7 6 5 4
0 7 6 5
0 0 7 6
0 0 0 7
Is there an easy way to do this, without using a for loop, such as:
for h=4:-1:1
b(1:h-1,h)=zeros(h-1,1);
b(h:length(a)+h-1,h)=a;
b(length(a)+h:length(a)+3,h)=zeros(4-h,1);
end
Thanks

采纳的回答

Honglei Chen
Honglei Chen 2013-9-20
You can use
toeplitz([1:7 0 0 0],[1 0 0 0])

更多回答(2 个)

Azzi Abdelmalek
Azzi Abdelmalek 2013-9-20
a=1:7
n=numel(a);
m=4;
b=[a';zeros(m-1,1)];
out=cell2mat(arrayfun(@(x) circshift(b,[x 0]),0:m-1,'un',0))

Azzi Abdelmalek
Azzi Abdelmalek 2013-9-20
a=1:7
m=4;
b=repmat([a zeros(1,m)]',1,m);
out=reshape(b(1:end-m),[],m)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by