How to create a meshgrid padded with a triangle of zeros in the upper-right and lower-left corners
2 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
More Answers (2)
Azzi Abdelmalek
on 20 Sep 2013
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))
0 Comments
Azzi Abdelmalek
on 20 Sep 2013
a=1:7
m=4;
b=repmat([a zeros(1,m)]',1,m);
out=reshape(b(1:end-m),[],m)
0 Comments
See Also
Categories
Find more on Multidimensional Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!