# Difficulty with LevelSpec. Product of empty set should be 1

I have a matrix

newm = {{{}, {}, {-p}}, {{d}, {e}, {p}}, {{g}, {h}, {i}}};
MatrixForm[newm};


whose elements are lists.

I would like to multiply the elements of a part of a row, for instance the last two elements of row 1, in such a way that the empty set contributes 1 to the product. This code does the job:

Apply[Times, {newm[[1, 2 ;; -1]]}, 2][[1]]


But it seems overly complicated, i.e. having to wrap the part newm[[1, 2 ;; -1]] in curly braces, and specify level 2 for the Times command, and then extract the first (only) element of the answer.

Is there a more elegant way ?

I have been experimenting with Levelspec but this is the only thing I can find that works.

• Why are you wrapping the individual elements in {}? Why don't you replace {-p} with -p, for instance, and replace the {}s with 1s? – march Oct 30 '15 at 4:51
• Thank you for responding, march. My matrix is an adjacency matrix for a graph with weighted, labelled edges. Hence each element is a list of real numbers, such as {p,p^2}. It is true that for this particular application, the lists are all either singleton sets such as {p}, or {1-p^2}, or the empty set {}. Therefore in this case I could pre-process the matrix by removing the curly braces from all the singletons, and replacing all the empty sets by 1. – Simon Oct 30 '15 at 4:55
• n = newm /. {} -> {1}; h @@ n[[1, 2 ;; -1, 1]] Use h as you please, for example h = Times – Dr. belisarius Oct 30 '15 at 4:57
• That's what I would do. In that case, you would do Times @@ newm[[1, 2 ;; -1]]. Perhaps you could post the more general case? – march Oct 30 '15 at 4:57
• Thank you both very much ! I am convinced that your approach is the best: Convert {} to 1 first. I realise I don't understand the part specification well. I should use [[1,2;;-1,1]] as belisarius is forth does, instead of [[1,2;;-1]], which I have been using. The 1,2 means start from the element in the 1st row and 2nd column. The -1 means continue until the last element (but why should that mean the last element of this particular row ?) And the final 1 seems to mean to take the first column ? But why ? I find the documentation a bit vague on this topic. – Simon Oct 30 '15 at 5:15

In more general case, as mentioned in comments:

newm = {{{}, {}, {2, 2}, {-p, p^2}}, {{d}, {}, {e}, {p}}, {{g}, {}, {h}, {i}}};
MatrixForm[newm]


One way is to raplace {} with {1} and we can take specific part from newm to apply Times to.

Or

Composition[
Apply[Times],
First,
Flatten[#, {{2}, {1}}] &,  (*transposition of ragged array*)
#[[1, 2 ;;]] &             (*row and row's part spec*)
] @ newm

-2 p