Re: Matrices & Compile
- To: mathgroup at smc.vnet.net
- Subject: [mg22575] Re: [mg22525] Matrices & Compile
- From: Andrzej Kozlowski <andrzej at tuins.ac.jp>
- Date: Sat, 11 Mar 2000 17:52:46 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
on 3/9/00 9:24 AM, Kurt Taretto at Kurt.Taretto at ipe.uni-stuttgart.de wrote:
>
> Hi,
>
> I'm making some functions using Compile, but I found some features of
> Compile which I don't fully
> understand yet. The following trivial function should take an nxn
> matrix and asign the value 1.0
> to the element (2,2) of that matrix:
>
> In[1]:=
> f = Compile[{{n, _Integer}, {a, _Real, 2}}, a[[2, 2]] = 1.0]
>
> Out[1]=
> CompiledFunction[{n, a}, a[[2, 2]] = 1., "-CompiledCode-"]
>
>
> The compilation was succesfull, but the function does not work:
>
> In[2]:=
> a = {{3, 2}, {1, 4}};
>
> In[3]:=
> f[2, a]
>
> Set::"setps": {{3, 2}, {1, 4}}; in assignment of part is not a symbol."
>
> Out[3]=
> 1.
>
> In[4]:=
> a
>
> Out[4]=
> {{3, 2}, {1, 4}}
>
> If I assign matrix a to an object b, everything goes well
>
> In[5]:=
> f = Compile[{{n, _Integer}, {a, _Real, 2}},
> Module[{b}, b = a; b[[2, 2]] = 1; b]]
>
> Out[5]=
> CompiledFunction[{n, a},
> Module[{b}, b = a; b[[2, 2]]= 1;b], "-CompiledCode-"]
>
> In[6]:=
> a = f[2, a]
>
> Out[6]=
> {{3., 2.}, {1., 1.}}
>
> The problem with this alternative is the unecessary memory requirement
> for b, and also the
> need for extra notation. I'm dealing with functions that take several
> large matrices as arguments,
> and do operations on their elements. Making statements like the above
> "b=a" makes the resulting code
> unnecesary complicated and more difficult to read. Is there any way out
> of this or did I make some
> simple mistake?
>
> Any help will be appreciated! Thanks!
>
> Kurt Taretto
>
>
>
The reason why your construction does not work is that Compile works just
like Function, in other when you call f[x,y], n and a in the body of your
function definition are literarly replaced by x and y. One possible way to
get round this is to use ReplacePart instead of Part in the body of Compile:
In[1]:=
f = Compile[{{n, _Integer}, {a, _Real, 2}}, ReplacePart[a, 1.0, {2, 2}]];
In[2]:=
a = {{3, 2}, {1, 4}};
In[3]:=
f[2, a]
Out[3]=
{{3., 2.}, {1., 1.}}
--
Andrzej Kozlowski
Toyama International University
JAPAN
http://sigma.tuins.ac.jp