swageta
swageta

Reputation: 305

Prolog: Matrix operations

I don't have a lot of experience in porgramming in Prolog. I am struggeling with writing rules for basic matrix operations. So I need these three operations for a matrix N:

size(+N,-Num): returns n if N is of size n x n
fetch(+N,+I,+J,-Value): returns the (I,J) value of N
store(+N,+I,+J,+Value,-NewN): replaces the (I,J) value of N

So for example I have a matrix like this:

[ [[b],[d,o],[m,o]],
  [[a],[oi,mi,d],[di,fi]],
  [[b],[d],[=]]         ]

I hope anyone can help me, thanks :)

EDIT: I think I solved the first two operations. Here the size(N,Num) operation:

size2(N, Ls) :-
   length(Ls, N).

size1(Mss, R, C) :-
   length(Mss, R),
   maplist(size2(C), Mss).

size(N,M):-
   size1(N,R,C),
   R = C,
   M is R.

Here the fetch(N,I,J,Value) operation:

fetch(Mat, Row, Col, Val) :- 
    nth1(Row, Mat, ARow), nth1(Col, ARow, Val).

But I am not sure how to write the store(N,I,J,Value,NewN) operation...

Upvotes: 1

Views: 283

Answers (1)

CapelliC
CapelliC

Reputation: 60014

You can use nth1/4 (I linked to nth0/4 since the docs are explicit on that entry), replacing both the row and the element in it, in similar way as you used in your fetch/4. Consider this sample

?- L=[a,b,c],I=3,N=x, nth1(I, L, Old, Temp), nth1(I, R, N, Temp).
L = [a, b, c],
I = 3,
N = x,
Old = c,
Temp = [a, b],
R = [a, b, x].

In R we have the third (I=3) element replaced in L.

So, all you need is to call 4 times nth1 in the correct order. First, you fetch the row to be modified, then you apply the element substitution, and then reinsert the row in the matrix.

The resulting code is fairly general, for instance (note I,J - here called U,V - aren't specified):

?- store([[1,2,3],[3,4,5],[7,8,9]],U,V,x,R).
U = V, V = 1,
R = [[x, 2, 3], [3, 4, 5], [7, 8, 9]] ;
U = 1,
V = 2,
R = [[1, x, 3], [3, 4, 5], [7, 8, 9]] ;
U = 1,
V = 3,
R = [[1, 2, x], [3, 4, 5], [7, 8, 9]] ;
...

Upvotes: 1

Related Questions