creating matrix with colon

2 views (last 30 days)
Aditya
Aditya on 22 Apr 2015
Edited: James Tursa on 22 Apr 2015
Hi
I am trying to create a matrix such that
a = [2 3 4];
b =zeros(3,length(-4:1:4));
b = (-a(1:3):1:a(1:3));
but this gives me an error
i know that a matrix of different row lengths cannot be created therefore i define the size at the start
what i intend to get is
b = [-2 -1 0 1 2 0 0 0 0;
-3 -2 -1 0 1 2 3 0 0;
-4 -3 -2 -1 0 1 2 3 4;]
i know this can be easily done via for loop but is there any way of doing this in single command?

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 22 Apr 2015
Edited: Andrei Bobrov on 22 Apr 2015
k = ones(3,1)*(-4:4);
[m,n] = size(k);
k2 = k.*rot90(triu(ones(size(k))),2);
b = full(spdiags(k2,1-m:n-1,m,n));
or
a = (2:4)';
b = bsxfun(@plus,-a,0:max(a));
b(bsxfun(@gt,b,a)) = 0;
or
bcell = arrayfun(@(x)-x:x,a,'un',0);

More Answers (0)

Categories

Find more on Operating on Diagonal Matrices 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!