Skip to content

Instantly share code, notes, and snippets.

@zikes
Created Dec 19, 2012
Embed
What would you like to do?
Matrix Transpose
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Matrix Transpose</title>
<script src="numbers.min.js"></script>
<script src="http://d3js.org/d3.v3.js"></script>
<style>
.button {
fill: steelBlue;
cursor: pointer;
}
</style>
</head>
<body>
<script>
var data = [
[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]
];
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
function transpose(){
data = numbers.matrix.transpose(data);
update_data();
}
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append('g')
.attr('transform','translate(120,0)')
.append('text')
.attr('class','button')
.on('click',transpose)
.text('Transpose');
var matrix = svg.append('g').attr('class','matrix');
update_data();
function update_data(){
var matrix_data = [];
data.forEach(function(d){
d.forEach(function(i){
matrix_data.push(i);
})
});
var groups = matrix.selectAll('g').data(matrix_data,function(d,i){return d});
groups.enter()
.append('g')
.append('text')
.attr('text-anchor','middle')
.text(String);
groups.transition(1000).delay(function(d,i){return i*25}).attr('transform',function(d){
var i = matrix_data.indexOf(d);
var tens = Math.floor(parseInt(i.toString(5),10)/10);
var ones = parseInt(i.toString(5),10) - (tens * 10);
return "translate("+(ones*20)+","+(tens*20)+")";
});
}
</script>
</body>
</html>
(function(){var require=function(file,cwd){var resolved=require.resolve(file,cwd||"/");var mod=require.modules[resolved];if(!mod)throw new Error("Failed to resolve module "+file+", tried "+resolved);var cached=require.cache[resolved];var res=cached?cached.exports:mod();return res};require.paths=[];require.modules={};require.cache={};require.extensions=[".js",".coffee",".json"];require._core={assert:true,events:true,fs:true,path:true,vm:true};require.resolve=function(){return function(x,cwd){if(!cwd)cwd="/";if(require._core[x])return x;var path=require.modules.path();cwd=path.resolve("/",cwd);var y=cwd||"/";if(x.match(/^(?:\.\.?\/|\/)/)){var m=loadAsFileSync(path.resolve(y,x))||loadAsDirectorySync(path.resolve(y,x));if(m)return m}var n=loadNodeModulesSync(x,y);if(n)return n;throw new Error("Cannot find module '"+x+"'");function loadAsFileSync(x){x=path.normalize(x);if(require.modules[x]){return x}for(var i=0;i<require.extensions.length;i++){var ext=require.extensions[i];if(require.modules[x+ext])return x+ext}}function loadAsDirectorySync(x){x=x.replace(/\/+$/,"");var pkgfile=path.normalize(x+"/package.json");if(require.modules[pkgfile]){var pkg=require.modules[pkgfile]();var b=pkg.browserify;if(typeof b==="object"&&b.main){var m=loadAsFileSync(path.resolve(x,b.main));if(m)return m}else if(typeof b==="string"){var m=loadAsFileSync(path.resolve(x,b));if(m)return m}else if(pkg.main){var m=loadAsFileSync(path.resolve(x,pkg.main));if(m)return m}}return loadAsFileSync(x+"/index")}function loadNodeModulesSync(x,start){var dirs=nodeModulesPathsSync(start);for(var i=0;i<dirs.length;i++){var dir=dirs[i];var m=loadAsFileSync(dir+"/"+x);if(m)return m;var n=loadAsDirectorySync(dir+"/"+x);if(n)return n}var m=loadAsFileSync(x);if(m)return m}function nodeModulesPathsSync(start){var parts;if(start==="/")parts=[""];else parts=path.normalize(start).split("/");var dirs=[];for(var i=parts.length-1;i>=0;i--){if(parts[i]==="node_modules")continue;var dir=parts.slice(0,i+1).join("/")+"/node_modules";dirs.push(dir)}return dirs}}}();require.alias=function(from,to){var path=require.modules.path();var res=null;try{res=require.resolve(from+"/package.json","/")}catch(err){res=require.resolve(from,"/")}var basedir=path.dirname(res);var keys=(Object.keys||function(obj){var res=[];for(var key in obj)res.push(key);return res})(require.modules);for(var i=0;i<keys.length;i++){var key=keys[i];if(key.slice(0,basedir.length+1)===basedir+"/"){var f=key.slice(basedir.length);require.modules[to+f]=require.modules[basedir+f]}else if(key===basedir){require.modules[to]=require.modules[basedir]}}};(function(){var process={};var global=typeof window!=="undefined"?window:{};var definedProcess=false;require.define=function(filename,fn){if(!definedProcess&&require.modules.__browserify_process){process=require.modules.__browserify_process();definedProcess=true}var dirname=require._core[filename]?"":require.modules.path().dirname(filename);var require_=function(file){var requiredModule=require(file,dirname);var cached=require.cache[require.resolve(file,dirname)];if(cached&&cached.parent===null){cached.parent=module_}return requiredModule};require_.resolve=function(name){return require.resolve(name,dirname)};require_.modules=require.modules;require_.define=require.define;require_.cache=require.cache;var module_={id:filename,filename:filename,exports:{},loaded:false,parent:null};require.modules[filename]=function(){require.cache[filename]=module_;fn.call(module_.exports,require_,module_,module_.exports,dirname,filename,process,global);module_.loaded=true;return module_.exports}}})();require.define("path",function(require,module,exports,__dirname,__filename,process,global){function filter(xs,fn){var res=[];for(var i=0;i<xs.length;i++){if(fn(xs[i],i,xs))res.push(xs[i])}return res}function normalizeArray(parts,allowAboveRoot){var up=0;for(var i=parts.length;i>=0;i--){var last=parts[i];if(last=="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up--;up){parts.unshift("..")}}return parts}var splitPathRe=/^(.+\/(?!$)|\/)?((?:.+?)?(\.[^.]*)?)$/;exports.resolve=function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if(typeof path!=="string"||!path){continue}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."};exports.normalize=function(path){var isAbsolute=path.charAt(0)==="/",trailingSlash=path.slice(-1)==="/";path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path};exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){return p&&typeof p==="string"}).join("/"))};exports.dirname=function(path){var dir=splitPathRe.exec(path)[1]||"";var isWindows=false;if(!dir){return"."}else if(dir.length===1||isWindows&&dir.length<=3&&dir.charAt(1)===":"){return dir}else{return dir.substring(0,dir.length-1)}};exports.basename=function(path,ext){var f=splitPathRe.exec(path)[2]||"";if(ext&&f.substr(-1*ext.length)===ext){f=f.substr(0,f.length-ext.length)}return f};exports.extname=function(path){return splitPathRe.exec(path)[3]||""}});require.define("__browserify_process",function(require,module,exports,__dirname,__filename,process,global){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}if(canPost){var queue=[];window.addEventListener("message",function(ev){if(ev.source===window&&ev.data==="browserify-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("browserify-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];process.binding=function(name){if(name==="evals")return require("vm");else throw new Error("No such module. (Possibly not yet loaded)")};(function(){var cwd="/";var path;process.cwd=function(){return cwd};process.chdir=function(dir){if(!path)path=require("path");cwd=path.resolve(dir,cwd)}})()});require.define("/numbers/basic.js",function(require,module,exports,__dirname,__filename,process,global){var basic=exports;basic.sum=function(arr){if(Object.prototype.toString.call(arr)==="[object Array]"){var total=0;for(var i=0;i<arr.length;i++){if(typeof arr[i]==="number")total=total+arr[i];else throw new Error("All elements in array must be numbers")}return total}else{throw new Error("Input must be of type Array")}};basic.subtraction=function(arr){if(Object.prototype.toString.call(arr)==="[object Array]"){var total=arr[arr.length-1];for(var i=arr.length-2;i>=0;i--){if(typeof arr[i]==="number")total-=arr[i];else throw new Error("All elements in array must be numbers")}return total}else{throw new Error("Input must be of type Array")}};basic.product=function(arr){if(Object.prototype.toString.call(arr)==="[object Array]"){var total=arr[0];for(var i=1,length=arr.length;i<length;i++){if(typeof arr[i]==="number")total=total*arr[i];else throw new Error("All elements in array must be numbers")}return total}else{throw new Error("Input must be of type Array")}};basic.square=function(num){return num*num};basic.binomial=function(n,k){var arr=[];function _binomial(n,k){if(n>=0&&k===0)return 1;if(n===0&&k>0)return 0;if(arr[n]&&arr[n][k]>0)return arr[n][k];if(!arr[n])arr[n]=[];return arr[n][k]=_binomial(n-1,k-1)+_binomial(n-1,k)}return _binomial(n,k)};basic.factorial=function(num){var i=2,o=1;while(i<=num){o*=i++}return o};basic.gcd=function(a,b){var c;b=+b&&+a?+b:0;a=b?a:1;while(b){c=a%b;a=b;b=c}return Math.abs(a)};basic.lcm=function(num1,num2){return Math.abs(num1*num2)/basic.gcd(num1,num2)};basic.random=function(arr,quant,allowDuplicates){if(arr.length===0){throw new Error("Empty array")}else if(quant>arr.length&&!allowDuplicates){throw new Error("Quantity requested exceeds size of array")}if(allowDuplicates===true){var result=[],i;for(i=0;i<quant;i++){result[i]=arr[Math.floor(Math.random()*arr.length)]}return result}else{return basic.shuffle(arr).slice(0,quant)}};basic.shuffle=function(array){var m=array.length,t,i;while(m){i=Math.floor(Math.random()*m--);t=array[m];array[m]=array[i];array[i]=t}return array};basic.max=function(array){return Math.max.apply(Math,array)};basic.min=function(array){return Math.min.apply(Math,array)};basic.range=function(start,stop,step){var array,i=0,len;if(arguments.length<=1){stop=start||0;start=0}step=step||1;if(stop<start){step=0-Math.abs(step)}len=Math.max(Math.ceil((stop-start)/step)+1,0);array=new Array(len);while(i<len){array[i++]=start;start+=step}return array};basic.isInt=function(n){return n%1===0};basic.divMod=function(a,b){if(!basic.isInt(a)||!basic.isInt(b))return false;return[Math.floor(a/b),a%b]};basic.powerMod=function(a,b,m){if(b<-1)return Math.pow(a,b)%m;if(b===0)return 1%m;if(b>=1){var result=1;while(b>0){if(b%2===1){result=result*a%m}a=a*a%m;b=b>>1}return result}if(b===-1)return basic.modInverse(a,m);if(b<1){return basic.powerMod(a,Math.pow(b,-1),m)}};basic.egcd=function(a,b){var x=+b&&+a?1:0,y=b?0:1,u=+b&&+a?0:1,v=b?1:0;b=+b&&+a?+b:0;a=b?a:1;while(b){var dm=basic.divMod(a,b),q=dm[0],r=dm[1];var m=x-u*q,n=y-v*q;a=b;b=r;x=u;y=v;u=m;v=n}return[a,x,y]};basic.modInverse=function(a,m){var r=basic.egcd(a,m);if(r[0]!=1)throw new Error("No modular inverse exists");return r[1]%m}});require.define("/numbers/calculus.js",function(require,module,exports,__dirname,__filename,process,global){var numbers=require("../numbers");var calculus=exports;calculus.pointDiff=function(func,point){var a=func(point-.001);var b=func(point+.001);return(b-a)/.002};calculus.riemann=function(func,start,finish,n,sampler){var inc=(finish-start)/n;var totalHeight=0;var i;if(typeof sampler==="function"){for(i=start;i<finish;i+=inc){totalHeight+=func(sampler(i,i+inc))}}else{for(i=start;i<finish;i+=inc){totalHeight+=func(i)}}return totalHeight*inc};function simpsonDef(func,a,b){var c=(a+b)/2;var d=Math.abs(b-a)/6;return d*(func(a)+4*func(c)+func(b))}function simpsonRecursive(func,a,b,whole,eps){var c=a+b,left=simpsonDef(func,a,c),right=simpsonDef(func,c,b);if(Math.abs(left+right-whole)<=15*eps){return left+right+(left+right-whole)/15}else{return simpsonRecursive(func,a,c,eps/2,left)+simpsonRecursive(func,c,b,eps/2,right)}}calculus.adaptiveSimpson=function(func,a,b,eps){eps=typeof eps==="undefined"?numbers.EPSILON:eps;return simpsonRecursive(func,a,b,simpsonDef(func,a,b),eps)};calculus.limit=function(func,point,approach){if(approach==="left"){return func(point-1e-15)}else if(approach==="right"){return func(point+1e-15)}else if(approach==="middle"){return(calculus.limit(func,point,"left")+calculus.limit(func,point,"right"))/2}else{throw new Error("Approach not provided")}};calculus.StirlingGamma=function(num){return Math.sqrt(2*Math.PI/num)*Math.pow(num/Math.E,num)};calculus.LanczosGamma=function(num){var p=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,1.5056327351493116e-7];var i;var g=7;if(num<.5)return Math.PI/(Math.sin(Math.PI*num)*calculus.LanczosGamma(1-num));num-=1;var a=p[0];var t=num+g+.5;for(i=1;i<p.length;i++){a+=p[i]/(num+i)}return Math.sqrt(2*Math.PI)*Math.pow(t,num+.5)*Math.exp(-t)*a}});require.define("/numbers.js",function(require,module,exports,__dirname,__filename,process,global){var numbers=exports;numbers.basic=require("./numbers/basic");numbers.calculus=require("./numbers/calculus");numbers.matrix=require("./numbers/matrix");numbers.prime=require("./numbers/prime");numbers.statistic=require("./numbers/statistic");numbers.useless=require("./numbers/useless");numbers.EPSILON=.001});require.define("/numbers/matrix.js",function(require,module,exports,__dirname,__filename,process,global){var matrix=exports;matrix.addition=function(arrA,arrB){if(arrA.length===arrB.length&&arrA[0].length===arrB[0].length){var result=new Array(arrA.length);for(var i=0;i<arrA.length;i++){result[i]=new Array(arrA[i].length);for(var j=0;j<arrA[i].length;j++){result[i][j]=arrA[i][j]+arrB[i][j]}}return result}else{throw new Error("Matrix mismatch")}};matrix.scalar=function(arr,val){for(var i=0;i<arr.length;i++){for(var j=0;j<arr[i].length;j++){arr[i][j]=val*arr[i][j]}}return arr};matrix.transpose=function(arr){var result=new Array(arr[0].length);for(var i=0;i<arr[0].length;i++){result[i]=new Array(arr.length);for(var j=0;j<arr.length;j++){result[i][j]=arr[j][i]}}return result};matrix.identity=function(n){var result=new Array(n);for(var i=0;i<n;i++){result[i]=new Array(n);for(var j=0;j<n;j++){result[i][j]=i===j?1:0}}return result};matrix.dotproduct=function(vectorA,vectorB){if(vectorA.length===vectorB.length){var result=0;for(var i=0;i<vectorA.length;i++){result+=vectorA[i]*vectorB[i]}return result}else{throw new Error("Vector mismatch")}};matrix.multiply=function(arrA,arrB){if(arrA[0].length===arrB.length){var result=new Array(arrA.length);for(var x=0;x<arrA.length;x++){result[x]=new Array(arrB[0].length)}var arrB_T=matrix.transpose(arrB);for(var i=0;i<result.length;i++){for(var j=0;j<result[i].length;j++){result[i][j]=matrix.dotproduct(arrA[i],arrB_T[j])}}return result}else{throw new Error("Array mismatch")}};matrix.determinant=function(m){var numRow=m.length;var numCol=m[0].length;if(numRow===2&&numCol===2){return m[0][0]*m[1][1]-m[0][1]*m[1][0]}var det=0;var row,col;var diagLeft,diagRight;for(col=0;col<numCol;col++){diagLeft=m[0][col];diagRight=m[0][col];for(row=1;row<numRow;row++){diagRight*=m[row][((col+row)%numCol+numCol)%numCol];diagLeft*=m[row][((col-row)%numCol+numCol)%numCol]}det+=diagRight-diagLeft}return det};matrix.rotate=function(point,degree,direction){if(point.length===2){var negate=direction==="clockwise"?-1:1;var radians=degree*(Math.PI/180);var transformation=[[Math.cos(radians),-1*negate*Math.sin(radians)],[negate*Math.sin(radians),Math.cos(radians)]];return matrix.multiply(transformation,point)}else{throw new Error("Only two dimensional operations are supported at this time")}};matrix.scale=function(point,sx,sy){if(point.length===2){var transformation=[[sx,0],[0,sy]];return matrix.multiply(transformation,point)}else{throw new Error("Only two dimensional operations are supported at this time")}};matrix.shear=function(point,k,direction){if(point.length===2){var xplaceholder=direction==="xaxis"?k:0;var yplaceholder=direction==="yaxis"?k:0;var transformation=[[1,xplaceholder],[yplaceholder,1]];return matrix.multiply(transformation,point)}else{throw new Error("Only two dimensional operations are supported at this time")}};matrix.affine=function(point,tx,ty){if(point.length===2){var transformation=[[1,0,tx],[0,1,ty],[0,0,1]];var newpoint=[[point[0][0]],[point[1][0]],[1]];var transformed=matrix.multiply(transformation,newpoint);return[[transformed[0][0]],[transformed[1][0]]]}else{throw new Error("Only two dimensional operations are supported at this time")}};matrix.rowScale=function(m,row,scale){var result=new Array(m.length);for(var i=0;i<m.length;i++){result[i]=new Array(m[i].length);for(var j=0;j<m[i].length;j++){if(i===row){result[i][j]=scale*m[i][j]}else{result[i][j]=m[i][j]}}}return result};matrix.rowSwitch=function(m,row1,row2){var result=new Array(m.length);for(var i=0;i<m.length;i++){result[i]=new Array(m[i].length);for(var j=0;j<m[i].length;j++){if(i===row1){result[i][j]=m[row2][j]}else if(i===row2){result[i][j]=m[row1][j]}else{result[i][j]=m[i][j]}}}return result};matrix.rowAddMultiple=function(m,from,to,scale){var result=new Array(m.length);for(var i=0;i<m.length;i++){result[i]=new Array(m[i].length);for(var j=0;j<m[i].length;j++){if(i===to){result[to][j]=m[to][j]+scale*m[from][j]}else{result[i][j]=m[i][j]}}}return result}});require.define("/numbers/prime.js",function(require,module,exports,__dirname,__filename,process,global){var basic=require("./basic");var prime=exports;prime.simple=function(val){if(val===1)return false;else if(val===2)return true;else if(val!==undefined){var start=1;var valSqrt=Math.ceil(Math.sqrt(val));while(++start<=valSqrt){if(val%start===0){return false}}return true}};prime.factorization=function(num){num=Math.floor(num);var root,factors=[],x,sqrt=Math.sqrt,doLoop=1<num&&isFinite(num);while(doLoop){root=sqrt(num);x=2;if(num%x){x=3;while(num%x&&(x+=2)<root){}}x=root<x?num:x;factors.push(x);doLoop=x!==num;num/=x}return factors};prime.millerRabin=function(n,k){if(arguments.length===1)k=20;if(n===2)return true;if(!basic.isInt(n)||n<=1||n%2===0)return false;var s=0,d=n-1;while(true){var dm=basic.divMod(d,2),quotient=dm[0],remainder=dm[1];if(remainder===1)break;s+=1;d=quotient}var tryComposite=function(a){if(basic.powerMod(a,d,n)===1)return false;for(var i=0;i<s;i++){if(basic.powerMod(a,Math.pow(2,i)*d,n)===n-1)return false}return true};for(var i=0;i<k;i++){var a=2+Math.floor(Math.random()*(n-2-2));if(tryComposite(a))return false}return true};prime.sieve=function(n){if(n<2)return[];var result=[2];for(var i=3;i<=n;i++){var not_multiple=false;for(var j in result){not_multiple=not_multiple||0===i%result[j]}if(!not_multiple){result.push(i)}}return result}});require.define("/numbers/statistic.js",function(require,module,exports,__dirname,__filename,process,global){var basic=require("./basic");var statistic=exports;statistic.mean=function(arr){var count=arr.length;var sum=basic.sum(arr);return sum/count};statistic.median=function(arr){return statistic.quantile(arr,1,2)};statistic.mode=function(arr){var counts={};for(var i=0,n=arr.length;i<n;i++){if(counts[arr[i]]===undefined)counts[arr[i]]=0;else counts[arr[i]]++}var highest;for(var number in counts){if(counts.hasOwnProperty(number)){if(highest===undefined||counts[number]>counts[highest])highest=number}}return Number(highest)};statistic.quantile=function(arr,k,q){var sorted,count,index;if(k===0)return Math.min.apply(null,arr);if(k===q)return Math.max.apply(null,arr);sorted=arr.slice(0);sorted.sort(function(a,b){return a-b});count=sorted.length;index=count*k/q;if(index%1===0)return.5*sorted[index-1]+.5*sorted[index];return sorted[Math.floor(index)]};statistic.report=function(array){return{mean:statistic.mean(array),firstQuartile:statistic.quantile(array,1,4),median:statistic.median(array),thirdQuartile:statistic.quantile(array,3,4),standardDev:statistic.standardDev(array)}};statistic.randomSample=function(lower,upper,n){var sample=[];while(sample.length<n){var temp=Math.random()*upper;if(lower<=temp<=upper){sample.push(temp)}}return sample};statistic.standardDev=function(arr){var count=arr.length;var mean=statistic.mean(arr);var squaredArr=[];for(var i=0;i<arr.length;i++){squaredArr[i]=Math.pow(arr[i]-mean,2)}return Math.sqrt(1/count*basic.sum(squaredArr))};statistic.correlation=function(arrX,arrY){if(arrX.length==arrY.length){var covarXY=statistic.covariance(arrX,arrY);var stdDevX=statistic.standardDev(arrX);var stdDevY=statistic.standardDev(arrY);return covarXY/(stdDevX*stdDevY)}else{throw new Error("Array mismatch")}};statistic.rSquared=function(source,regression){var residualSumOfSquares=basic.sum(source.map(function(d,i){return basic.square(d-regression[i])}));var totalSumOfSquares=basic.sum(source.map(function(d){return basic.square(d-statistic.mean(source))}));return 1-residualSumOfSquares/totalSumOfSquares};statistic.exponentialRegression=function(arrY){var n=arrY.length;var arrX=basic.range(1,n);var xSum=basic.sum(arrX);var ySum=basic.sum(arrY);var yMean=statistic.mean(arrY);var yLog=arrY.map(function(d){return Math.log(d)});var xSquared=arrX.map(function(d){return d*d});var xSquaredSum=basic.sum(xSquared);var yLogSum=basic.sum(yLog);var xyLog=arrX.map(function(d,i){return d*yLog[i]});var xyLogSum=basic.sum(xyLog);var a=(yLogSum*xSquaredSum-xSum*xyLogSum)/(n*xSquaredSum-xSum*xSum);var b=(n*xyLogSum-xSum*yLogSum)/(n*xSquaredSum-xSum*xSum);var fn=function(x){if(typeof x==="number"){return Math.exp(a)*Math.exp(b*x)}else{return x.map(function(d){return Math.exp(a)*Math.exp(b*d)})}};fn.rSquared=statistic.rSquared(arrY,arrX.map(fn));return fn};statistic.linearRegression=function(arrX,arrY){var n=arrX.length;var xSum=basic.sum(arrX);var ySum=basic.sum(arrY);var xySum=basic.sum(arrX.map(function(d,i){return d*arrY[i]}));var xSquaredSum=basic.sum(arrX.map(function(d){return d*d}));var xMean=statistic.mean(arrX);var yMean=statistic.mean(arrY);var b=(xySum-1/n*xSum*ySum)/(xSquaredSum-1/n*xSum*xSum);var a=yMean-b*xMean;return function(x){if(typeof x==="number"){return a+b*x}else{return x.map(function(d){return a+b*d})}}};statistic.covariance=function(set1,set2){if(set1.length==set2.length){var n=set1.length;var total=0;var sum1=basic.sum(set1);var sum2=basic.sum(set2);for(var i=0;i<n;i++){total+=set1[i]*set2[i]}return(total-sum1*sum2/n)/n}else{throw new Error("Array mismatch")}}});require.define("/numbers/useless.js",function(require,module,exports,__dirname,__filename,process,global){var useless=exports;useless.collatz=function(n,result){result.push(n);if(n==1){return}else if(n%2===0){useless.collatz(n/2,result)}else{useless.collatz(3*n+1,result)}}});require.define("/numbers.js",function(require,module,exports,__dirname,__filename,process,global){var numbers=exports;numbers.basic=require("./numbers/basic");numbers.calculus=require("./numbers/calculus");numbers.matrix=require("./numbers/matrix");numbers.prime=require("./numbers/prime");numbers.statistic=require("./numbers/statistic");numbers.useless=require("./numbers/useless");numbers.EPSILON=.001;window.numbers=numbers});require("/numbers.js")})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment