快学ScalaChapter11操作符练习解答12.8提供一个Matrix类—你可以选择需要的是一个2*2的矩阵,任意大小的正方形矩阵,或m*n的矩阵。支持+和*操作。*操作应同样适用于单值,例如mat*2。单个元素可以通过mat(row,col)得到importscala.collection.mutable.ArrayBuffer/***@authorLiRuiqi*/classMatrix(privatevaldata:Array[Int],privatevalnrow:Int){valcols=(data.length.toFloat/nrow).ceil.toIntprivatevalmatrixData:Array[Array[Int]]={valresult:Array[Array[Int]]=Array.ofDim[Int](nrow,cols)for(i-0untilnrow){for(j-0untilcols){valindex=i*cols+jresult(i)(j)=if(data.isDefinedAt(index))data(index)else0}}result}overridedeftoString={varstr=matrixData.map((p:Array[Int])={p.mkString(,)}).mkString(\n)}def*(a:Matrix)={if(this.cols!=a.nrow)println(error!)else{valdata:ArrayBuffer[Int]=ArrayBuffer()for(i-0tothis.nrow-1){for(j-0toa.cols-1){varnum=0for(b-0tothis.cols-1){num+=this.matrixData(i)(b)*a.matrixData(b)(j)}data+=num}}newMatrix(data.toArray,this.nrow)}}def*(a:Int)={valdata:ArrayBuffer[Int]=ArrayBuffer()for(i-0tothis.matrixData.length-1){for(j-0tothis.matrixData(0).length-1){data+=this.matrixData(i)(j)*a}}newMatrix(data.toArray,this.matrixData.length)}def+(a:Matrix)={if(this.nrow!=a.nrow||this.cols!=a.cols)println(error!)else{valdata:ArrayBuffer[Int]=ArrayBuffer()for(i-0tothis.matrixData.length-1){for(j-0tothis.matrixData(0).length-1){data+=this.matrixData(i)(j)+a.matrixData(i)(j)}}newMatrix(data.toArray,this.matrixData.length)}}defmat(row:Int,col:Int)={matrixData(row-1)(col-1)}}objectQuestion8{defmain(args:Array[String]):Unit={valm=newMatrix(Array(1,2,3,4),2)valn=newMatrix(Array(1,3,5,8),2)println(m+\n)println(n+\n)println(m*n+\n)println(m+n+\n)println(m.mat(2,2)+\n)println(m*10+\n)}}