KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lsmp > djepExamples > MatrixExample


1 /* @author rich
2  * Created on 26-Feb-2004
3  *
4  * This code is covered by a Creative Commons
5  * Attribution, Non Commercial, Share Alike license
6  * <a HREF="http://creativecommons.org/licenses/by-nc-sa/1.0">License</a>
7  */

8
9 package org.lsmp.djepExamples;
10 import org.nfunk.jep.*;
11 import org.lsmp.djep.matrixJep.*;
12 import org.lsmp.djep.matrixJep.nodeTypes.*;
13 /**
14  * Examples using vectors and matricies
15  */

16 public class MatrixExample {
17     static MatrixJep j;
18     
19     public static void main(String JavaDoc args[]) {
20         j = new MatrixJep();
21         j.addStandardConstants();
22         j.addStandardFunctions();
23         j.addComplex();
24         j.setAllowUndeclared(true);
25         j.setImplicitMul(true);
26         j.setAllowAssignment(true);
27
28         // parse and evaluate each equation in turn
29

30         doStuff("[1,2,3]"); // Value: [1.0,2.0,3.0]
31
doStuff("[1,2,3].[4,5,6]"); // Value: 32.0
32
doStuff("[1,2,3]^[4,5,6]"); // Value: [-3.0,6.0,-3.0]
33
doStuff("[1,2,3]+[4,5,6]"); // Value: [5.0,7.0,9.0]
34
doStuff("[[1,2],[3,4]]"); // Value: [[1.0,2.0],[3.0,4.0]]
35
doStuff("[[1,2],[3,4]]*[1,0]"); // Value: [1.0,3.0]
36
doStuff("[1,0]*[[1,2],[3,4]]"); // Value: [1.0,2.0]
37
doStuff("[[1,2],[3,4]]*[[1,2],[3,4]]"); // Value: [[7.0,10.0],[15.0,22.0]]
38
// vectors and matricies can be used with assignment
39
doStuff("x=[1,2,3]"); // Value: [1.0,2.0,3.0]
40
doStuff("x+x"); // Value: [2.0,4.0,6.0]
41
doStuff("x . x"); // Value: 14.0
42
doStuff("x^x"); // Value: [0.0,0.0,0.0]
43
doStuff("y=[[1,2],[3,4]]"); // Value: [[1.0,2.0],[3.0,4.0]]
44
doStuff("y * y"); // Value: [[7.0,10.0],[15.0,22.0]]
45
// accessing the elements on an array or vector
46
doStuff("ele(x,2)"); // Value: 2.0
47
doStuff("ele(y,[1,2])"); // Value: 2.0
48
// using differentation
49
doStuff("x=2"); // 2.0
50
doStuff("y=[x^3,x^2,x]"); // [8.0,4.0,2.0]
51
doStuff("z=diff(y,x)"); // [12.0,4.0,1.0]
52
doStuff("diff([x^3,x^2,x],x)");
53         System.out.println("dim(z) "+((MatrixVariableI) j.getVar("z")).getDimensions());
54     }
55
56     public static void doStuff(String JavaDoc str) {
57         try {
58             Node node = j.parse(str);
59             Node proc = j.preprocess(node);
60             Node simp = j.simplify(proc);
61             Object JavaDoc value = j.evaluate(simp);
62             //j.println(proc);
63
j.print(simp);
64             System.out.print("\t dim "+((MatrixNodeI) simp).getDim());
65             System.out.println("\tvalue " + value.toString());
66         }
67         catch(ParseException e) { System.out.println("Parse error "+e.getMessage()); }
68         catch(Exception JavaDoc e) { System.out.println("evaluation error "+e.getMessage()); e.printStackTrace(); }
69     }
70 }
71
Popular Tags