Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Maple expression x*y to Matlab for the result x.*y?

Tags:

matlab

maple

A Maple expression (for example, x^3+x*y) can be converted to Matlab by

with(CodeGeneration):
Matlab(x^3+x*y);

However, in Matlab, there are two kinds of product: A*B and A.*B. The above way will give x^3+x*y. Is there a convenient way to get the result x.^3+x.*y?

like image 370
renphysics Avatar asked Oct 22 '22 19:10

renphysics


2 Answers

The language definition for Maple's CodeGeneration[Matlab] can be extended to handle various instances of the elementwise tilde (~) operator.

Since 'x*~y' seems to automatically simplify to `~`[`*`](x, ` $`, y), and since there appears to be a hard-coded error emitted by the presence of the name " $", then that name is substituted by NULL in the usage code below.

> restart:

> with(CodeGeneration): with(LanguageDefinition):

> LanguageDefinition:-Define("NewMatlab", extend="Matlab",
>   AddFunction("`~`[`^`]", [Vector,integer]::Vector,
>               proc(X,Y)
>                  Printer:-Print(X,".^",Y)
>              end proc,
>               numeric=double),
>   AddFunction("`~`[`*`]", [Vector,integer]::Vector,
>               proc(X,Y)
>                  Printer:-Print(X,".*",Y)
>               end proc,
>               numeric=double));

> expr:=''x^~y + x^~3 + x*~y'':

> Translate(subs(` $`=NULL, expr ), language="NewMatlab");

cg = x.^y + x.^3 + x.*y;

> p := proc(x,y)
>         x^~y + x^~3 + x*~y;
>      end proc:

> f := subs(` $`=NULL, eval(p) ):
> Translate(f, language="NewMatlab");

function freturn = f(x, y)
  freturn = x.^y + x.^3 + x.*y;
like image 168
acer Avatar answered Oct 27 '22 14:10

acer


For whatever it's worth, Maple 2015 can do this translation directly, without the extra help kindly provided by acer:

> f := (x,y)->x^~y + x^~3 + x*~y:
> CodeGeneration:-Matlab(f);
function freturn = f(x, y)
  freturn = x .^ y + x .^ 3 + x .* y;
like image 36
saforrest Avatar answered Oct 27 '22 14:10

saforrest