1
votes

I'm trying to simulate a product of a matrix with a vector using these two predicates:

eva([], [], []).
eva([A|A1], [W], [Res|R1]) :-
    vectormultiplication(A, W, Res),
    eva(A1, W, R1).

vectormultiplication([A], [W], [A*W]).
vectormultiplication([A|A1], [W|W1], [A*W|Out1]) :-
    vectormultiplication(A1, W1, Out1).

Where the [A|A1] in eva is a matrix (or a list of lists), [W] is a vector (a list),and [Res|R1] is the resulting product. vectormultiplication is supposed to go multiply each list in the list with the vector W. However, this strategy just produces a false response. Is there anything apparent that I'm doing wrong here that prevents me from getting the desired product? I'm currently using SWI Prolog version 5.10

2

2 Answers

2
votes

Well, your first problem is that you think A*W is going to do anything by itself. In Prolog, that's just going to create the expression A*W, no different from *(A,W) or foo(A, W)--without is/2 involved, no actual arithmetic reduction will take place. That's the only real problem I see in a quick glance.

2
votes

you have 2 other problems apart that evidenced by Daniel (+1): here a cleaned up source

eva([], _, []).  % here [] was wrong
eva([A|A1], W, [Res|R1]) :- % here [W] was wrong
    vectormultiplication(A, W, Res),
    eva(A1, W, R1).

vectormultiplication([A], [W], [M]) :-
    M is A*W.
vectormultiplication([A|A1], [W|W1], [M|Out1]) :-
    M is A*W,
    vectormultiplication(A1, W1, Out1).

test:

?- eva([[1,2],[3,5]],[5,6],R).
R = [[5, 12], [15, 30]]

when handling lists, it's worth to use maplist if available

eva(A, W, R) :-
    maplist(vectormultiplication1(W), A, R).

vectormultiplication1(W, A, M) :-
    maplist(mult, A, W, M).

mult(A, W, M) :-
    M is A*W.

Note I changed the order of arguments of vectormultiplication1, because the vector is a 'constant' in that loop, and maplist append arguments to be 'unrolled'.