/// <summary> /// compute vector dot product /// </summary> /// <param name="otherVector"></param> /// <returns></returns> public float DotProduct(SparseVec otherVector) { if (otherVector == null) { throw new ArgumentNullException("otherVector"); } if (otherVector.Dim != Dim) { string expMsg = string.Format("different dimensions vec1={0} vec2={1}", this.ToString(), otherVector.ToString()); throw new ArgumentException(expMsg, "otherVector"); } float result = 0; if (Count < 1) { return(0.0f); } if (otherVector.Count < 1) { return(0.0f); } int i1 = 0; int i2 = 0; while (i1 < this.Count && i2 < otherVector.Count) { int index1 = Indices[i1]; int index2 = otherVector.Indices[i2]; if (index1 == index2) { float mul = Values[i1] * otherVector.Values[i2]; result += mul; i1++; i2++; } else if (index1 < index2) { i1++; } else { i2++; } } return(result); }
public SparseVec Subtract(SparseVec otherVec) { int v1 = 0; int v2 = 0; List <float> vals = new List <float>(); List <int> idx = new List <int>(); while (v1 < this.Count || v2 < otherVec.Count) { int v1Idx = this.Indices[v1]; int v2Idx = otherVec.Indices[v2]; if (v1Idx == v2Idx) { float sub = this.Values[v1] - otherVec.Values[v2]; if (sub != 0) { vals.Add(sub); idx.Add(v1Idx); } v1++; v2++; } else if (v1Idx < v2Idx) { // this.Values[v1] - 0.0 vals.Add(this.Values[v1]); idx.Add(v1Idx); v1++; } else { vals.Add(0.0f - otherVec.Values[v2]); idx.Add(v2Idx); v2++; } } SparseVec sp = new SparseVec(this.Dim, idx, vals); return(sp); }