MEVIS3000
MEVIS3000

Reputation: 541

Matlab recursive function to generate a matrix

I'm struggling with this task:

Create a recursive function that takes n as an argument and creates a matrix like this, in this case n = 3:

 0     1     2     3     2     1     0
 1     1     2     3     2     1     1
 2     2     2     3     2     2     2
 3     3     3     3     3     3     3

I already came up with this:

function AA =  A(n)
    if n == 0
        AA (1,1) = 0;
    else
        AA = n*ones(n+1,2*n+1);
        AA(1:n, [1:n, n+3:end]) = A(n-1);
    end  
end

But the output seems to have a weird shift on the RHS:

 0     1     2     3     3     2     1
 1     1     2     3     3     2     1
 2     2     2     3     3     2     2
 3     3     3     3     3     3     3

Can someone help?

Upvotes: 3

Views: 1194

Answers (2)

Daniel
Daniel

Reputation: 36710

I think both answers already existing can be simplified. For the recursive solution use:

function AA =  A(n)
    if n == 0
        AA = 0;
    else
        h=A(n-1);
        AA = n*ones(n+1,2*n+1);
        AA(1:n,1:n)=h(:,1:n);
        AA(1:n,n+2:end)=h(:,n:end);
    end  
end

The important point is to index the column n of the intermediate result twice to duplicate it, one in h(:,1:n) and once in h(:,n:end).

If you are looking for a vectorized / faster solution simply use:

bsxfun(@max,[0:N-1].',[0:N-1 N-2:-1:0])

For MATLAB 2016b or later, implicit expansion can be used:

max([0:N-1].',[0:N-1 N-2:-1:0])

Upvotes: 7

GameOfThrows
GameOfThrows

Reputation: 4510

I have a no loop answer which is a little unorthodox, but it works fine and is very fun to write (or to say I am bored at work at the moment)..

N =3;
A = repmat(0:N,N+1,1);
M = triu(A,1);
B = repmat((0:N)',1,N+1);
L = fliplr(flipud(triu(flipud(B))));
P = M+L;
Rep = fliplr(P(:,1:N));
answer = [P,Rep];

This one uses the triu to generate the progressive pattern in the matrix, and does some fun constructing to create the final matrix:

N = 2;

answer =

 0     1     2     1     0
 1     1     2     1     1
 2     2     2     2     2

N = 4;

answer =

 0     1     2     3     4     3     2     1     0
 1     1     2     3     4     3     2     1     1
 2     2     2     3     4     3     2     2     2
 3     3     3     3     4     3     3     3     3
 4     4     4     4     4     4     4     4     4

Advantage: Uses no loop, will definitely be faster for large N I assume.I highly advise running line by line to see what the output is, so you understand how it is constructed step by step.

Upvotes: 4

Related Questions