Created
May 31, 2012 12:43
-
-
Save OpenGamma-Blog/2843161 to your computer and use it in GitHub Desktop.
Testing Java Code in Maths Libraries 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%% A translation of http://commons.apache.org/math/userguide/linear.html Example in section 3.2 | |
%% Apache Commons Math is refered to as ACM | |
clear all; close all; clc; | |
% assume the jars in in the pwd, add to java class path | |
javaaddpath([pwd,'/commons-math3-3.0.jar']); | |
javaaddpath([pwd,'/octave.jar']); | |
% basenames for classes we'll be using | |
ACMBasename='org.apache.commons.math3.linear.'; | |
octaveBasename='org.octave.'; | |
% Create a real matrix with two rows and three columns | |
matrixData=[1.,2.,3.;2.,5.,3.]; % the data | |
tmp=javaObject([octaveBasename,'Matrix'],reshape(matrixData,1,6),[2,3]); % conversion temporary | |
m=javaObject([ACMBasename,'Array2DRowRealMatrix'],tmp.asDoubleMatrix()); % invoke ACM (double[][]) constructor | |
% One more with three rows, two columns | |
matrixData2=[1.,2.;3.,5.;1.,7.]; % the data | |
tmp=javaObject([octaveBasename,'Matrix'],reshape(matrixData2,1,6),[3,2]); % conversion temporary | |
n=javaObject([ACMBasename,'Array2DRowRealMatrix'],tmp.asDoubleMatrix()); % invoke ACM (double[][]) constructor | |
% Now multiply m by n | |
p = m.multiply(n); % ACM multiply | |
disp('ACM row count result:'); | |
disp(['row dimension=',num2str(p.getRowDimension())]) % ACM result, rows = 2 | |
disp(['row dimension=',num2str(p.getColumnDimension())]) % ACM result, columns = 2 | |
disp('') | |
disp('ACM dgemm result:'); | |
p.toString() % ACM print result | |
% ACM invert p, using LU decomposition | |
ludecomp = javaObject([ACMBasename,'LUDecomposition'],p); % ACM LUDecomposition class | |
pInverse = ludecomp.getSolver().getInverse(); % method invocation chaining also works in Octave! ACM inverse via LU. | |
disp('ACM inverse result:'); | |
pInverse.toString() | |
% ship back to octave | |
ACMInverse=java2mat(pInverse.getData()) | |
%% Now we do the same in native octave | |
octavep = matrixData * matrixData2; | |
disp('Octave dgemm result:'); | |
octavep | |
disp('Octave inverse result:'); | |
inv(octavep) | |
%% compute errors... | |
printf('Norm error Octave vs ACM = %20.12f\n',norm(inv(octavep)-ACMInverse)) | |
%% helper function to make java double{[]...} into octave native | |
function [ret] = java2mat(v) | |
n=length(v); | |
ret=zeros(1,n); | |
for k = 1:length(v) | |
ret(k)=v(k); | |
end | |
ret =ret' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment