creating matrix with colon

2 次查看(过去 30 天)
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?

采纳的回答

Andrei Bobrov
Andrei Bobrov 2015-4-22
编辑:Andrei Bobrov 2015-4-22
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);

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Elementary Math 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by