2
votes

I have the question how to construct the matrix of this type with the more time-saving. The task is that the user enters the natural number (n=1,2,3,4,5...) and the R has to print the matrix of such type (below the type of matrix for n=4). I observe that the first and second columns are symmetrical to columns 6th and 7th, and it's enough to print correctly the 1st and second colums in the left. Also I observed that the 3rd column is obtained as second column + c(0,0,1,1,1,0,0) that corresponds 1+1+1=3 - number of this column. But I don't understand, what is the algorithm of this matrix for general case (f.e. for n=6, the dim is 2n-1 x 2n-1 (nrow x ncol). Is it the most easy variant to construct this matrix column by column or function outer allows to simplify that task?

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

1 Answers

5
votes

Yes, outer can make this easier. Combined with pmin it gives you the behavior you're looking for

n <- 4

series <- c(seq_len(n-1), n, rev(seq_len(n-1)))
# [1] 1 2 3 4 3 2 1

outer(series, series, pmin)
     # [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,]    1    1    1    1    1    1    1
# [2,]    1    2    2    2    2    2    1
# [3,]    1    2    3    3    3    2    1
# [4,]    1    2    3    4    3    2    1
# [5,]    1    2    3    3    3    2    1
# [6,]    1    2    2    2    2    2    1
# [7,]    1    1    1    1    1    1    1

Here it is as a function

myfun <- function(n) {
                series <- c(seq_len(n-1), n, rev(seq_len(n-1)))
                return(outer(series, series, pmin))
            }
myfun(4)