How to build a matrix like this

if we have a number n, we want a matrix like this:
So one simple example is:
What is the best way to build this?

Antworten (4)

Stephen23
Stephen23 am 18 Aug. 2017
Bearbeitet: Stephen23 am 18 Aug. 2017

1 Stimme

>> N = 4;
>> V = N:-1:1;
>> bsxfun(@min,V,repmat(V(:),1,N))
ans =
4 3 2 1
3 3 2 1
2 2 2 1
1 1 1 1
José-Luis
José-Luis am 18 Aug. 2017

1 Stimme

n = 4;
result = repmat((n:-1:1),n,1) - tril(cumsum(tril(ones(n)))-1)
Kuifeng
Kuifeng am 18 Aug. 2017

0 Stimmen

The following works, not the 'best' way...
n = 5;
A = [n:-1:1]';
for i = 2:n
A(:,i) = A(:,i-1);
A([1:i],i) = n-(i-1);
end

3 Kommentare

José-Luis
José-Luis am 18 Aug. 2017
Bearbeitet: José-Luis am 18 Aug. 2017
It's somewhat of a bad habit to use square brackets when declaring arrays.
Stephen23
Stephen23 am 18 Aug. 2017
Bearbeitet: Stephen23 am 18 Aug. 2017
It is better to use parentheses around an already existing vector:
A = (n:-1:1)';
rather than using the concatenation operator. The editor has warning for this:
Kuifeng
Kuifeng am 18 Aug. 2017
Thank you Jose-Luis and Stephen, I noticed this red wave below for some time already, but didnt know why. You cleared my doubt. Good to learn.
Robert U
Robert U am 18 Aug. 2017
Bearbeitet: Robert U am 18 Aug. 2017

0 Stimmen

Hi Rui Zhu,
another possibility:
function [ A ] = SpecMatrice( n )
tic
A = zeros(n);
for ik = 1:n
A(1:ik,1:ik) = A(1:ik,1:ik) + 1;
end
t = toc;
sprintf('MySolution took %.2f µs',t*1e6)
end
On my PC that solution is for low values of n faster than the presented above. Here values for n=4:
Solution 1 took 806.82 µs
Solution 2 took 888.93 µs
Solution 3 took 441.34 µs
MySolution took 109.33 µs
For high values of n solution 2 & 3 gain speed a lot while solution 1 and MySolution get slowlier due to looping.
Kind regards,
Robert

Diese Frage ist geschlossen.

Gefragt:

am 18 Aug. 2017

Geschlossen:

am 20 Aug. 2021

Community Treasure Hunt

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

Start Hunting!

Translated by