modified stdlib vector a bit, added matrix, removed ChrisTest

This commit is contained in:
Chris Fadden
2015-05-16 00:03:36 -04:00
parent 795f8715ff
commit d166dc9b5f
14 changed files with 562 additions and 440 deletions

166
stdlib/matrix.krak Normal file
View File

@@ -0,0 +1,166 @@
import vector:*;
import io:*;
typedef matrix (Destructable) {
var data: vector<double>;
var rows: int;
var cols: int;
///******************************
// Constructors
///*****************************/
//Constructor with no arguments
//No matrix is made
fun construct(): matrix* {
rows = 0;
cols = 0;
data.construct();
return this;
}
//Constructor with single argument
//Creates an N x N matrix
fun construct(size: int): matrix* {
rows = size;
cols = size;
data.construct(rows*cols);
return this;
}
//Constructor with two arguments
//Creates an N x M matrix
fun construct(r: int, c: int): matrix* {
rows = r;
cols = c;
data.construct(rows*cols);
return this;
}
///****************************
// Utility Functions
///***************************/
//Test using indexing at 0
fun test0(i: int, j: int): bool {
var index = i*rows + j;
if(index > (rows * cols - 1) ) {
print("Index (");
print(i);
print(", ");
print(j);
println(") is out of bounds.");
print("Max index = (");
print(rows-1);
print(", ");
print(cols-1);
println(").");
return false;
}
return true;
}
//Test using indexing at 1
fun test1(i: int, j: int): bool {
var index = (i-1)*rows + (j-1);
if(index > (rows * cols - 1) ) {
print("Index (");
print(i);
print(", ");
print(j);
println(") is out of bounds.");
print("Max index = (");
print(rows);
print(", ");
print(cols);
println(").");
return false;
}
return true;
}
//Access matrix element
fun at(i: int, j: int): double {
var index = i*rows + j;
if(test0(i,j))
return data.at(index);
return 0;
}
//Set matrix element
fun set(i: int, j: int, num: double): void {
var index = i*rows + j;
if(test0(i,j))
data.set(index,num);
return;
}
fun printMatrix(): void {
for(var i: int = 0; i < rows; i++;)
{
for(var j: int = 0; j < cols; j++;)
{
print(at(i,j));
print(" ");
}
println(" ");
}
return;
}
///**************************
// Linear Algebra Functions
//**************************/
fun transpose(): void {
var val1: double;
var val2: double;
for(var n: int = 0; n <= rows - 2; n++;)
for(var m: int = n+1; m <= rows - 1; m++;){
val1 = at(n, m);
val2 = at(m, n);
set(n, m, val2);
set(m, n, val1);
}
return;
}
};//end Matrix class

View File

@@ -13,6 +13,14 @@ typedef vector<T> (Destructable) {
data = new<T>(8);
return this;
}
fun construct(newSize: int): vector<T>*{
size = newSize;
available = newSize;
data = new<T>(newSize);
return this;
}
fun destruct(): void {
delete<T>(data);
@@ -39,6 +47,8 @@ typedef vector<T> (Destructable) {
println("Vector access out of bounds! Retuning 0th element as sanest option");
print("Vector tried to access element: ");
println(index);
print("Max Index of vector: ");
println(size-1);
return data[0];
}
return data[index];