1

I'm very new to prolog, specifically, SWI-PL. I've seen several related questions about computing matrix-vector products. It seems that they're all unnecessarily complicated or use libraries. This question contains a nice first principles implementation of the dot product as:

dot([], [], 0).
dot([H1|T1], [H2|T2], Result) :- 
  Prod is H1 * H2,
  dot(T1, T2, Remaining),
  Result is Prod + Remaining.

It seems like we could get a nice definition of a matrix vector product (MVP) by applying dot to every element of the matrix and every element of the list. Something like:

maplist(dot, M, V, R).

or

maplist(maplist(dot), M, V, R).

where M is a matrix (list of lists), v is a vector, and R is the result. however, these consistently give false, for values such as:

[[2,3],[4,5]],[1,0]

what am I missing?

false
  • 10,264
  • 13
  • 101
  • 209
Evan Rosica
  • 1,182
  • 1
  • 12
  • 22

1 Answers1

3

maplist concurrently iterates the three lists. So that means that for a call:

maplist(dot, M, V, R)

it means that dot(Mi, Vi, Ri) (this is "pseudo-code") will hold for all i. But this does not match with the types: dot expects the three parameters to be lists, now the element of a vector Vi is a number, not a sublist. If you multiply a matrix M with a vector V, the i-th value of the Result is: dot(Mi, V, Ri). Since a dot product is commutative, we can swap the operands, so dot(V, Mi, Ri) holds as well.

So that means that we can define the matrix-vector product as:

matvecprod(M, V, R) :-
    maplist(dot(V), M, R).

For example:

?- matvecprod([[1,-1,2], [0,-3,1]], [2,1,0], R).
R = [1, -3]. 
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Thanks very much for taking the time to answer. The example you give is generating an error for some reason: `ERROR: Type error: "atom" expected, found "dot([2,1,0])" (a compound)' – Evan Rosica Oct 22 '18 at 08:03
  • @EvanRosica: I can not reproduce this locally. What distribution+version of Prolog do you use? – Willem Van Onsem Oct 22 '18 at 08:13
  • Nevermind, it seems the error was on my end. Something else in my database file was causing a conflict. You might want to change the name of the example to match your definition. – Evan Rosica Oct 22 '18 at 08:13