TransWikia.com

Update Matrix entry from Java

Mathematica Asked by Gouz on January 19, 2021

I found the following example online (which works fine) for sending commands from Java:

ml.putFunction("EvaluatePacket", 1);
ml.putFunction("Plus", 2);
ml.put(3);
ml.put(3);
ml.endPacket();

I need to follow the same tactic to update through a loop, the items of some Matrix.
For example, the Mathematica expression I want to evaluate would be:

MyMatrix[[1]] = {3, 4};

What is the equivalent Java code for this action? The following does not seem to update MyMatrix because the last print shows it like it was originally.

ml.putFunction("EvaluatePacket", 1);
ml.putFunction("Set", 2);
ml.putFunction("Part", 2);
ml.put("MyMatrix");
ml.put(1);
ml.putFunction("List", 2);
ml.put(3.);
ml.put(4.);
ml.endPacket();
ml.discardAnswer();

System.out.println(ml.evaluateToOutputForm("MyMatrix", 0));

On the contrary, this works:

ml.evaluateToOutputForm("MyMatrix[[1]] = {3.0, 4.0};", 0);
System.out.println(ml.evaluateToOutputForm("MyMatrix", 0));

Here is a full example showing the problem:

import com.wolfram.jlink.*;

public class Mathematica {

public static void main(String[] args) {

    KernelLink ml = null;
    String jLinkDir = "C:Program FilesWolfram ResearchMathematica12.0SystemFilesLinksJLink";
    System.setProperty("com.wolfram.jlink.libdir", jLinkDir);

    try {
        ml = MathLinkFactory.createKernelLink("-linkmode launch -linkname 'C:Program FilesWolfram ResearchMathematica12.0MathKernel.exe'");
        // Get rid of the initial InputNamePacket the kernel will send when it is launched.
        ml.discardAnswer();

        ml.evaluate("MyMatrix = {{1,2},{3,4}}");
        ml.discardAnswer();
        System.out.println(ml.evaluateToOutputForm("MyMatrix", 0));

        ml.putFunction("EvaluatePacket", 1);
        ml.putFunction("Set", 2);
        ml.putFunction("Part", 2);
        ml.put("MyMatrix");
        ml.put(1);
        ml.putFunction("List", 2);
        ml.put(5.);
        ml.put(6.);
        ml.endPacket();
        ml.discardAnswer();

        System.out.println(ml.evaluateToOutputForm("MyMatrix", 0));

        ml.evaluate("MyMatrix[[1]]={5.,6.};");
        ml.discardAnswer();
        System.out.println(ml.evaluateToOutputForm("MyMatrix", 0));

    } catch (MathLinkException e) {
        System.out.println("Fatal error opening link: " +
                e.getMessage());
    }
}
}

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP