creating matrix with colon

1 Ansicht (letzte 30 Tage)
Aditya
Aditya am 22 Apr. 2015
Bearbeitet: James Tursa am 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?

Akzeptierte Antwort

Andrei Bobrov
Andrei Bobrov am 22 Apr. 2015
Bearbeitet: Andrei Bobrov am 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);

Weitere Antworten (0)

Kategorien

Mehr zu Elementary Math finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by