Multi-dimensional or jagged array when dealing with matrix in C#? -
i think title quite clear, i'll write personal opinions here.
consider matrix of numbers, equivalent representations in c# code double[,]
, double[][]
respectively. when using multi-dimensional array (2d in specific situation), can seen 1 doesn't have check either there null reference of double[]
or size of rows same, allows better understanding of core problem. descirbes matrix more accurately point of view, since in cases matrix should treated single entity rather list of arrays.
but using multi-dimensional array may result in more lines of code. if 1 wants apply math operations on it, say, transposition, have use nested loops like
var row = mat.getlength(0); var col = mat.getlength(1); var newmat = new double[col, row]; (var = 0; < row; i++) { (var j = 0; j < col; j++) { newmat[j, i] = mat[i, j]; } }
with jagged array, can write
var newmat = enumerable.range(0, mat[0].length - 1). select(i => mat.select(r => r[i]).toarray()).toarray();
i'm not sure 1 better. create own subroutine unless there no solution provided .net, prefer latter. multi-dimensional array have advantages like. teach me how choose between them?
it's not lines of code problem, efficiency of code itself.
if had sparse matrix (matrix zeros), want use jagged matrix because iterating through two-dimensional matrix searching non-zero elements waste time.
however, if had matrix , wanted find determinant, simpler use method of co-factors on it. if you're not familiar method, involves breaking matrix smaller matrices, 2x2 version can perform a*d-b*c
. isn't possible jagged matrices.
Comments
Post a Comment