matrix - Addition of two matrices in SWI prolog -


i need addition of 2 matrices , swi prolog code of tried. answer wrong here. want corrected it.

:- use_module(library(clpfd)).  m_add(m1, m2, m3) :- maplist(mm_helper(m2), m1, m3).  mm_helper(m2, i1, m3) :- maplist(dot(i1), m2, m3).  dot(v1, v2, p) :- maplist(sum,v1,v2,p).  sum(n1,n2,n3) :- n3 n1+n2. 

when give question follows,

?- m_add([[2,1,3],[4,2,5]],[[4,0,1],[1,7,1]],r). 

the answer appears this.

r = [[[6, 1, 4], [3, 8, 4]], [[8, 2, 6], [5, 9, 6]]]. 

but answer should be,

r = [[6, 1, 4],[5, 9, 6]]. 

actually, it's simpler think:

m_add(m1, m2, m3) :- maplist(maplist(sum), m1, m2, m3). sum(x,y,z) :- z x+y. 

test:

?- m_add([[2,1,3],[4,2,5]],[[4,0,1],[1,7,1]],r). r = [[6, 1, 4], [5, 9, 6]]. 

if dealing integers, plus/3 can handy, can compute 'backward':

m_plus(m1, m2, m3) :- maplist(maplist(plus), m1, m2, m3).  ?- m_plus([[2,1,3],[4,2,5]],[[4,0,1],[1,7,1]],r). r = [[6, 1, 4], [5, 9, 6]].  ?- m_plus([[2,1,3],[4,2,5]],b,$r). b = [[4, 0, 1], [1, 7, 1]]. 

$r it's swi-prolog 'trick' remembered top level variables...

a final note: clp(fd) it's powerful library, if don't need actual capabilities, best stick native arithmetic...


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -