public void Get_AddIntList_ReturnAMultiplicationTable() { var table = new MatrixMultiplication(); var array = new int[] { 1, 2, 3, 4 }; var arrayTable = table.Get(array); //row 1 Assert.AreEqual(arrayTable[1][1], 1); Assert.AreEqual(arrayTable[1][2], 2); Assert.AreEqual(arrayTable[1][3], 3); Assert.AreEqual(arrayTable[1][4], 4); //row 2 Assert.AreEqual(arrayTable[2][1], 2); Assert.AreEqual(arrayTable[2][2], 4); Assert.AreEqual(arrayTable[2][3], 6); Assert.AreEqual(arrayTable[2][4], 8); //row 3 Assert.AreEqual(arrayTable[3][1], 3); Assert.AreEqual(arrayTable[3][2], 6); Assert.AreEqual(arrayTable[3][3], 9); Assert.AreEqual(arrayTable[3][4], 12); //row 4 Assert.AreEqual(arrayTable[4][1], 4); Assert.AreEqual(arrayTable[4][2], 8); Assert.AreEqual(arrayTable[4][3], 12); Assert.AreEqual(arrayTable[4][4], 16); }
public static void Main() { MatrixMultiplication MM = new MatrixMultiplication(); MM.ReadMatrix(); MM.MultiplyMatrix(); MM.PrintMatrix(); }
public IActionResult FormMatrixMultiplicationAssembly(MatrixMultiplication matrixMultiplication) { if (matrixMultiplication.MatrixA != null && matrixMultiplication.MatrixB != null) { MatrixMultiplicationASM multiplicationASM = new MatrixMultiplicationASM(); _multiplicationASM.Result = multiplicationASM.multiplyASM(matrixMultiplication.MatrixA, matrixMultiplication.MatrixB); } return(View(_multiplicationASM)); }
public MethodsController(IHostingEnvironment environment, Options options) { _hostingEnvironment = environment; _options = options; _jacobiMethodCPP = new JacobiMethod(); _jacobiMethodCPP.Implementation = "C++ is a high-level, general-purpose programming language created by Bjarne Stroustrup as an extension of the C programming language."; _multiplicationASM = new MatrixMultiplication(); _multiplicationASM.Implementation = "In computer programming, assembly language(or assembler language), often abbreviated asm, is any low - level programming language in which there is a very strong correspondence between the instructions in the language and the architecture's machine code instructions."; }
private static void RunMatrixMultiplication() { const int n = 1500 - 1; var resultM = new Real[n * n]; var resultC = new Real[n * n]; var left = new Real[n * n]; var right = new Real[n * n]; Benchmark.Run(Loops, () => MatrixMultiplication.Initialise(left, right, n), () => MatrixMultiplication.Initialise(left, right, n), () => AssertAreEqual(resultM, resultC, n, n), () => MatrixMultiplication.Managed(resultM, left, right, n), () => MatrixMultiplication.Cuda(resultC, left, right, n)); }
public void F64MatrixMultiplication_MultiplyVectorF64Multiply_Predefined() { var a = new F64Matrix(new double[4] { 1, 2, 3, 4 }, 2, 2); var v = new double[2] { 1, 2 }; var actual = new double[2]; MatrixMultiplication.MultiplyVectorF64(a, v, actual); var expected = new double[] { 5.0, 11.0 }; CollectionAssert.AreEqual(expected, actual); }
private static void RunMatrixMultiplication(Gpu aleaGpu, CudaAccelerator ilGpu) { const int n = 1500 - 1; var resultM = new Real[n * n]; var resultC = new Real[n * n]; var left = new Real[n * n]; var right = new Real[n * n]; Benchmark.Run(Loops, () => MatrixMultiplication.Initialise(left, right, n), () => MatrixMultiplication.Initialise(left, right, n), () => AssertAreEqual(resultM, resultC, n, n), () => MatrixMultiplication.Managed(resultM, left, right, n), () => MatrixMultiplication.Alea(aleaGpu, resultC, left, right, n), () => MatrixMultiplication.IlGpu(ilGpu, resultC, left, right, n)); }
public void MatrixMultication_Smoke_Test() { var N = 2; int[,] A = new int[N, N], B = new int[N, N]; A[0, 0] = 1; A[0, 1] = 2; A[1, 0] = 1; A[1, 1] = 4; B[0, 0] = 2; B[0, 1] = 0; B[1, 0] = 1; B[1, 1] = 2; var result = MatrixMultiplication.Multiply(A, B); Assert.AreEqual(4, result[0, 0]); Assert.AreEqual(4, result[0, 1]); Assert.AreEqual(6, result[1, 0]); Assert.AreEqual(8, result[1, 1]); }
public void F64MatrixMultiplication_F64MatrixMultiply_Predefined() { var a = new F64Matrix(new double[6] { 1, 2, 3, 4, 5, 6 }, 2, 3); var b = new F64Matrix(new double[6] { 7, 8, 9, 10, 11, 12 }, 3, 2); var actual = new F64Matrix(a.RowCount, b.ColumnCount); MatrixMultiplication.MultiplyF64(a, b, actual); var expected = new F64Matrix(new double[4] { 58, 64, 139, 154 }, 2, 2); Assert.AreEqual(expected, actual); }
public void GetQuadrant() { var sut = new MatrixMultiplication(); Matrix matrix1 = new Matrix(new double[, ] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }); Matrix matrix2 = new Matrix(new double[, ] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }); var mult = sut.MultiplyMatrices(matrix1, matrix2); //int m = matrix1.ColumnSize, n = matrix1.RowSize; //var quadrant = matrix1.SubMatrix(m/2, m, n/2, n); }
public async Task <List <MatrixMultiplication> > RunTask(InputParametrs input) { Data data = new Data(input.m, input.n, input.l); Stopwatch stopwatch = new Stopwatch(); for (int i = 0; i < 5; i++) { stopwatch.Start(); MatrixMultiplication matrixMultiplication = new MatrixMultiplication(data); matrixMultiplication.Multiply(); matrices.Add(matrixMultiplication); stopwatch.Stop(); matrixMultiplication.elapsedMs = stopwatch.ElapsedMilliseconds; Console.WriteLine(stopwatch.ElapsedMilliseconds); stopwatch.Reset(); data.m += input.mStep; data = new Data(data.m, data.n, data.l); } Console.WriteLine("-----------------------------"); for (int i = 0; i <= 5; i++) { stopwatch.Start(); MatrixMultiplication matrixMultiplication = new MatrixMultiplication(data); matrixMultiplication.Multiply(); matrices.Add(matrixMultiplication); stopwatch.Stop(); matrixMultiplication.elapsedMs = stopwatch.ElapsedMilliseconds; Console.WriteLine(stopwatch.ElapsedMilliseconds); stopwatch.Reset(); data.l += input.lStep; data = new Data(data.m, data.n, data.l); } //For matlab linear canvas Debug.Write("time = ["); foreach (var m in matrices) { Debug.Write(" " + m.elapsedMs); } Debug.Write(" ];"); Debug.WriteLine(" "); Debug.Write("m = [" + input.m); for (int i = 0; i < matrices.Count - 1; i++) { if (i < 5) { Debug.Write(" " + (input.m += input.mStep)); } else { Debug.Write(" " + (input.m)); } } Debug.Write(" ];"); Debug.WriteLine(" "); Debug.Write("n = ["); for (int i = 0; i < matrices.Count; i++) { Debug.Write(" " + input.n); } Debug.Write(" ];"); Debug.WriteLine(" "); return(matrices); }
private static void MatrixMultiplicationTest(int[] sizes, int expected) { int actual = MatrixMultiplication.MinimumOperations(sizes); Assert.AreEqual(expected, actual); }
static void Main(string[] args) { // StringProblems //Test calls for Reverse string string input = "jacob"; Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray()))); input = "jake"; Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray()))); input = ""; Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray()))); input = "jdshjdh@#$%^&)"; Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray()))); ReplaceSpaces.TestReplaceSpacesInplace(); Anagrams.TestIsAnagramAlgo(); StringRotation.TestIsThisRotatedString(); RemoveDuplicates.TestRemoveDuplicatesFromString(); StringToLongConverter.TestStringToLong(); RegexMatching.TestMatch(); SumOfTwoNumbersInArray.TestSumOfTwoNumbersInArray(); SumOfThreeNumbersInArray.TestSumOfThreeNumbersInArray(); PairInSortedArrayClosestToAParticularValue.TestPairInSortedArrayClosestToAParticularValue(); PalindromeInStringPermutation.TestPalindromeInStringPermutation(); EditDistanceBetweenStrings.TestEditDistanceBetweenStrings(); AnagramIsPalindrome.TestAnagramIsPalindrome(); GreatestPalindrome.TestGreatestPalindrome(); ReverseStringWithoutVowels.TestReverseStringWithoutVowels(); LongestSubstringWithKDistinctChars.TestLongestSubstringWithKDistinctChars(); // Pattern Matching NativePatternMatching.TestNativePatternMatching(); KMPPatternMatching.TestKMPPatternMatching(); BoyerMoorePatternMatching.TestPatternMatching(); RabinKarp.TestRabinKarp(); //Console.ReadLine(); //Array Problems ArrayOfNumsIncrement.TestIncrementArrayOfNumbers(); MajorityElement.TestFindMajorityElement(); Merge2SortedArrays.TestMergeSortedArrays(); MaxDistanceInArray.TestMaxDistanceInArray(); MovingAverage.TestMovingAverage(); TotalAverage.TestTotalAverage(); ArrayWithGreaterElementToRight.TestArrayWithGreaterElementToRight(); WaterCollectedInPuddleShownByHistogram.TestWaterCollectedInPuddleShownByHistogram(); CountOfPairsWhichSumUpToGivenSum.TestCountOfPairsWhichSumUpToGivenSum(); //Median.TestGetMedianOf2SortedArray(); // Sorting Problems SelectionSort.TestSorting(); BubbleSort.TestSorting(); InsertionSort.TestSorting(); ShellSort.TestSorting(); MergeSort.TestMergeSort(); QuickSort.TestQuickSort(); HeapSortTester.TestHeapSort(); CountingSort.TestSorting(); RadixSort.TestRadixSort(); DutchNationalFlag.TestDutchNationalFlag(); SortedSquares.TestSortedSquares(); // Matrix Problem Rotate_Matrix_90_degree.TestRotateMatrix(); Matrix_Column_Rows_0.TestMakeRowColZero1(); Matrix_Column_Rows_0.TestMakeRowColZero2(); RotateMatrix180.TestRotateMatrix180(); SumOfMatrixElementsFormedByRectangleWithCoordinates.TestSumOfMatrixElements(); SortedArrayFromSortedMatrix.TestSortedArrayFromSortedMatrix(); SearchWordInMatrix.TestSearchWordInMatrix(); MaxOnesInRow.TestMaxOnesInRow(); MatrixAsTriangle.TestMatrixAsTriangle(); MinRangeInMatrix.TestMinRangeInMatrix(); PrintMatrixAsSnake.TestPrintMatrixAsSnake(); PrintMatrixInSpiral.TestPrintMatrixInSpiral(); MaxSqAreaInBinaryMatrix.TestMaxRectAreaInBinaryMatrix(); TicTacToeWinner.TestTicTacToeWinner(); WaterfallCreation.TestWaterfallCreation(); // Linked list Problems DeleteLinkedListNode.TestDeleteFirstNode(); DeleteDuplicatesFromLinkedList.TestDeleteDuplicates(); NthLastElementOfLinkedList.TestNthLastNodeOfLinkedList(); DeleteNodeWithDirectReference.TestDeleteNode(); AddNumbers.TestAddNumbersRepresentedByLinkedList(); CopyLinkedListWithRandomNode.TestGetCopiedLinkedListWithRandomNode(); CommonElementInTwoLinkedList.TestCommonElement(); ReverseAdjacentNodesInLinkedList.TestReverseAdjacentNodes(); MergeSortedLinkedList.TestMerge(); CycleInLinkedList.TestStartOfCycleInLinkedList(); MedianForCircularLinkedList.TestGetMedian(); ReverseLinkedList.TestReverseLinkedList(); SortedCircularLinkedList.TestCircularLinkedList(); // stack and queue problem ThreeStackWithOneArray.TestThreeStackWithOneArray(); StackWithMinElement.TestStackWithMinElement(); StackOfPlates.TestStackOfPlates(); SortAStack.TestSortAStackAscending(); WellFormedExpression.TestWellFormedExpression(); QueueVia2Stack.TestQueueVia2Stack(); LRUCache.TestLRUCache(); EvaluatePrefixNotation.TestGetPrefixNotationResult(); EvaluateInflixNotation.TestGetInflixNotationResults(); EvaluatePostfixNotation.TestGetPostfixNotationResult(); TestCircularQueue.TestCircularQueueWithDifferentCases(); LargestAreaInHistogram.TestLargestAreaInHistogram(); TextEditerWithUndo.TestTextEditerWithUndo(); //Recursion Problem TowerOfHanoi.TestTowerOfHanoi(); MaxSumOfConsecutiveNums.TestMaxSumOfConsecutiveNums(); // Back tracking problems Sudoku.TestSudokuSolver(); HamiltonianCycle.TestHamiltonianCycle(); GraphColoringWithMColors.TestGraphColoringWithMColors(); MakeLargestIsland.TestMakeLargestIsland(); //Misc Problem MinNumOfCoins.TestMinNumOfCoins(); IsPrime.TestCheckPrime(); SquareRoot.TestCalculateSquareRoot(); CreditCardCheck.TestLuhnAlgo(); ExcelFirstRowConversion.TestCovertExcelColumnToLong(); Skyline.TestSkyline(); SumOfSquaresWithoutMultiplication.TestSumOfSquares(); MergeIntervals.TestMergeIntervals(); WidthOfCalendar.TestWidthOfCalendar(); JosephusProblem.TestJosephusProblem(); // Permutation and Combination problem ShuffleAList.TestFisherYatesAlgo(); CombinationsOfBinaryString.TestCombinationsOfBinaryString(); AllCombinationsOfString.TestAllCombinationsOfString(); AllPermutationsOfString.TestAllPermutationsOfString(); PhoneNumberToWords.TestPhoneNumberToWords(); AllNumbersInRangeWithDifferentDigits.TestAllNumbersInRangeWithDifferentDigits(); DivideSetIntoTwoEqualSetsWithMinSumDiff.TestDivideSetIntoTwoEqualSetsWithMinSumDiff(); PowerSet.TestPowerSet(); AllCombinationsOfParenthesis.TestAllCombinationsOfParenthesis(); GoodDiceRoll.TestGoodDiceRoll(); PermutationsOfValidTime.TestPermutationsOfValidTime(); // Tree Problems TreeFromExpression.TestCreateTreeFromExpression(); TestBinarySearchTree.TestDifferentOperationsOnBST(); AncestorOfTwoNodesInBST.TestAncestorOfTwoNodesInBST(); CheckBTisBST.TestCheckBTisBST(); MaxSumOnTreeBranch.TestMaxSum(); WalkTheTree.TestWalkTheTree(); SkewedBSTToCompleteBST.TestConvertSkewedBSTToCompleteBST(); CheckIfTheTreeIsBalanced.TestIsTreeBalanced(); LinkedListOfTreeNodesAtEachDepth.TestCreateLinkedListOfTreeNodesAtEachDepth(); PrintBinaryTreeNodeAtEachLevel.TestPrintBinaryTreeNodeAtEachLevel(); PrintBinaryTreeNodeAtEachLevelSpirally.TestPrintBinaryTreeNodeAtEachLevelSpirally(); TreeSubtreeOfAnother.TestMatchTree(); AncestorOfTwoNodesInBT.TestGetAncestorOfTwoNodesInBT(); AncestorOfMultiNodesInBT.TestAncestorOfMultiNodesInBT(); LinkedListFromLeavesOfBT.TestLinkedListFromLeavesOfBT(); ExteriorOfBT.TestPrintExteriorOfBT(); DepthOfTree.TestGetDepthOfTree(); TreeToColumns.TestTreeToColumns(); KthSmallestElementFromBST.TestKthSmallestElementFromBST(); MakeBSTFromPreOrder.TestMakeBSTFromPreOrder(); MirrorATree.TestMirrorATree(); CloneABTWithRandPointer.TestCloneABTWithRandPointer(); TreeWithInorderAndPreorder.TestTreeWithInorderAndPreorder(); TreeWithInorderAndPostorder.TestTreeWithInorderAndPostorder(); TreePathSumsToValue.TestTreePathSumsToValue(); AllPathInNArayTree.TestAllPathInNArayTree(); SerializeDeserializeBinaryTree.TestSerializeDeserializeBinaryTree(); SerializeDeserializeAnNaryTree.TestSerializeDeserializeAnNaryTree(); AncestorOfTwoNodesInNaryTree.TestAncestorOfTwoNodesInNaryTree(); AbsOfMaxAndSecondMaxDepthInBT.TestGetAbsOfMaxAndSecondMaxDepthInBT(); // Trie problems CreateAndSearchSimpleTrie.TestCreateAndSearchSimpleTrie(); // ToDo: have a problem of suffix trees ShortestPrefix.TestGetShortestPrefixNotPresentInStringSet(); // Dynamic Programming problems LongestCommonSubsequence.TestGetLongestCommonSubsequence(); LongestPalindromeSubString.TestGetLongestPalindromeSubString(); LongestPalindromicSubsequence.TestGetLongestPalindromicSubsequence(); MaximumAs.TestGetMaximumAs(); MinNumberOfJumps.TestGetMinimumNumberOfJumps(); LongestCommonSubString.TestGetLongestCommonSubString(); KnapSackProblem.TestGetTheMaximumValueWithLimitedWeight(); TreeCuttingProblem.TestGetTreeCuttingToMaximizeProfits(); WordBreaking.TestBreakTheWords(); DistanceOfWords.TestDistanceOfWords(); LongestIncreasingSubSequence.TestLongestIncreasingSubSequence(); MinCostPath.TestMinCostPath(); DifferentWaysForCoinChange.TestDifferentWaysForCoinChange(); MatrixMultiplication.TestMatrixMultiplication(); BinomialCoefficient.TestBinomialCoefficient(); BoxStacking.TestBoxStacking(); WordWrapping.TestWordWrapping(); MaxSubMatrixWithAllOnes.TestMaxSubMatrixWithAllOnes(); LongestSubStringWithEqualSum.TestLongestSubStringWithEqualSum(); PartitionArrayIntoEqualSumSets.TestPartitionArrayIntoEqualSumSets(); MaxSumRectangle.TestMaxSumRectangle(); RegularExpressionMatch.TestRegularExpressionMatch(); NumRepresentedByPerfectSquares.TestNumRepresentedByPerfectSquares(); LongestCommonSubsequenceInSameString.TestLongestCommonSubsequenceInSameString(); StringDecodeAsAlphabets.TestStringDecodeAsAlphabets(); BalloonBursting.TestBalloonBursting(); TravellingSalesmanProblem.TestTravellingSalesmanProblem(); MaxSumWithoutAdjacentElements.TestMaxSumWithoutAdjacentElements(); MaxPathThroughMatrix.TestMaxPathThroughMatrix(); BrickLaying.TestBrickLaying(); JobSchedullingWithConstraints.TestJobSchedullingWithConstraints(); EggDropMinTrials.TestEggDropMinTrials(); // Graph Problems ShortestPath.TestGetShortestPathBetween2Vertex(); CycleInDirectedGraph.TestIsCycleInDirectedGraph(); CycleInUnDirectedGraph.TestIsCycleInUnDirectedGraph(); SolveAMaze.TestSolveAMaze(); AllPathsGivenStartEndVertex.TestGetAllPathsInGraphFromStartVertexToEndVertex(); AllPaths.TestGetAllPathsInGraphFromStartVertex(); ColorVertices.TestColorVerticesWithDifferentColor(); CheckBipartiteGraph.TestCheckBipartiteGraph(); TransformOneWordToAnother.TestGetTransformation(); ConstraintsVerification.TestConstraintsVerification(); ExtendedContactsInSocialNetwork.TestComputeExtendedContacts(); CourseScheduling.TestCourseScheduling(); SnakeAndLadder.TestSnakeAndLadder(); IsGraphATree.TestIsGraphATree(); ReverseGraph.TestReverseGraph(); StronglyConnectedGraph.TestStronglyConnectedGraph(); ConnectedComponents.TestConnectedComponents(); ContinentalDivide.TestContinentalDivide(); CloneGraph.TestCloneGraph(); Wordament.TestWordament(); // ShortestPathAlgo FloydWarshall.TestFloydWarshall(); DijkstraAlgorithm.TestDijkstraAlgorithm(); BellmanFord.TestBellmanFord(); TravelFromLeftToRightInMatrix.TestTravelFromLeftToRightInMatrix(); HeuristicSearch.TestHeuristicSearch(); AStar.TestAStar(); ShortestPathWhenObstaclesRemoved.TestShortestPathWhenObstaclesRemoved(); ShortestDistanceFromRoomsToGates.TestShortestDistanceFromRoomsToGates(); //MaxFlow FordFulkersonEdmondKarp.TestFordFulkersonEdmondKarp(); MinCut.TestMinCut(); MaximumBipartiteMatching.TestMaximumBipartiteMatching(); //Minimum Spanning Tree KruskalAlgorithm.TestKruskalAlgorithm(); PrimsAlgorithm.TestPrimsAlgorithm(); //Heap problems BasicMaxHeap.TestMaxHeap(); BasicMinHeap.TestMinHeap(); TestMinHeapMap.DoTest(); TestPriorityQueue.Run(); MedianForAStreamOfNumbers.TestMedianForAStreamOfNumbers(); //DisjointSets TestingDisjointSet.Run(); //TestWeightedDisjointSetsWithPathCompression.Run(); // this runs slow, hence commenting it //Geometry ClosestPairOfPoints.TestClosestPairOfPoints(); RectangleIntersection.TestRectangleIntersection(); LineSegmentIntersection.TestLineSegmentIntersection(); ConvexHull.TestConvexHull(); KClosestPointToOrigin.TestKClosestPointToOrigin(); //Greedy Algorithm HuffmanCoding.TestHuffmanCoding(); //Randomized Algorithm RandomGeneration.TestRandomGeneration(); // Bit Algorithms IntHaveOppositeSigns.TestIntHaveOppositeSigns(); Parity.TestParity(); //Math Problem ZerosInFactorial.TestZerosInFactorial(); GetAllPrimeFactors.TestGetAllPrimeFactors(); NumberOfFactors.TestNumberOfFactors(); AllFactors.TestAllFactors(); MultiplyLongNumbers.TestMultiplyLongNumbers(); NextLargestPermutation.TestNextLargestPermutation(); AllPrimesTillN.TestAllPrimesTillN(); PascalsTriangle.TestPascalsTriangle(); SubtractLongNumbers.TestSubtractLongNumbers(); //Search problems SearchInSortedRotatedArray.TestSearchInSortedRotatedArray(); KClosestElementInArray.TestKClosestElementInArray(); SearchInSortedMatrix.TestSearchInSortedMatrix(); BinarySearchUnbounded.TestBinarySearchUnbounded(); LinkedListSublistSearch.TestLinkedListSublistSearch(); NoOfOccuranceInSortedArray.TestNoOfOccuranceInSortedArray(); GetSmallestInSortedRotatedArray.TestGetSmallestInSortedRotatedArray(); //Distributed algorithms KWayMerge.TestKWayMerge(); Console.ReadLine(); }
static void Main(string[] args) { int[,] Matrix_1, Matrix_2; string[] FileString; int M1, N1 = 0, M2, N2; using (var file = new StreamReader(Path.GetFullPath("Inlet.txt"))) { int i; string[] Aux; string CheckString = ""; for (i = 0; ; i++) { CheckString = file.ReadLine(); if (CheckString == "------") { break; } N1 = CheckString.Split(' ').Length; } M1 = i; for (i = 0; !file.EndOfStream; i++) { CheckString = file.ReadLine(); } M2 = i; Aux = CheckString.Split(' '); N2 = Aux.Length; file.Close(); } using (var file = new StreamReader(Path.GetFullPath("Inlet.txt"))) { Matrix_1 = new int[M1, N1]; int i, j; for (i = 0; i < M1; i++) { FileString = file.ReadLine().Split(' '); for (j = 0; j < N1; j++) { Matrix_1[i, j] = int.Parse(FileString[j]); } } file.ReadLine(); Matrix_2 = new int[M2, N2]; for (i = 0; i < M2; i++) { FileString = file.ReadLine().Split(' '); for (j = 0; j < N2; j++) { Matrix_2[i, j] = int.Parse(FileString[j]); } } } Matrix Matrix1 = new Matrix(Matrix_1, M1, N1); Matrix Matrix2 = new Matrix(Matrix_2, M2, N2); Matrix MatrixSum, MatrixMultiplication, MatrixDifferent; MatrixSum = Matrix.Summ(Matrix1, Matrix2); MatrixDifferent = Matrix.Diff(Matrix1, Matrix2); MatrixMultiplication = Matrix.Multipication(Matrix1, Matrix2); Console.WriteLine("Сумма двух матриц: "); MatrixSum.PrintMatrix(); Console.WriteLine(); Console.WriteLine("Разность двух матриц: "); MatrixDifferent.PrintMatrix(); Console.WriteLine(); Console.WriteLine("Произведение двух матриц: "); MatrixMultiplication.PrintMatrix(); }
public static NDArray <TData> Dot <TData>(this NDArray <TData> np1, NDArray <TData> np2) { dynamic prod = new NDArray <TData>(); dynamic np1Dyn = np1.Data.ToArray(); dynamic np2Dyn = np2.Data.ToArray(); var dataType = typeof(TData); int dimensionSum = np1.Shape.Count + np2.Shape.Count; switch (dimensionSum) { case 2: { prod.Shape = new int[] { 1 }; switch (dataType.Name) { case ("Double"): prod.Data = ScalarProduct1D.MuliplyScalarProd1DDouble((double[])np1Dyn, (double[])np2Dyn); break; case ("Float"): prod.Data = ScalarProduct1D.MuliplyScalarProd1Dfloat((float[])np1Dyn, (float[])np2Dyn); break; //case ("Complex") : prod.Data = ScalarProduct1D.Mult((float[])np1Dyn,(float[])np2Dyn); break; //case ("Quaternion") : prod.Data = ScalarProduct1D.MuliplyScalarProd1Dfloat((float[])np1Dyn,(float[])np2Dyn); break; } break; } case 3: { int[] dim0 = np1.Shape.ToArray(); int[] dim1 = np2.Shape.ToArray(); int iterator = np1.Shape[1]; prod.Shape = new int[] { dim0[0], dim1[1] }; switch (dataType.Name) { case ("Double"): prod.Data = MatrixMultiplication.MatrixMultiplyDoubleMatrix((double[])np1Dyn, (double[])np2Dyn, dim0, dim1); break; case ("Float"): prod.Data = MatrixMultiplication.MatrixMultiplyfloatMatrix((float[])np1Dyn, (float[])np2Dyn, dim0, dim1); break; case ("Complex"): prod.Data = MatrixMultiplication.MatrixMultiplyComplexMatrix((Complex[])np1Dyn, (Complex[])np2Dyn, dim0, dim1); break; case ("Quaternion"): prod.Data = MatrixMultiplication.MatrixMultiplyQuaternionMatrix((Quaternion[])np1Dyn, (Quaternion[])np2Dyn, dim0, dim1); break; } break; } case 4: { int[] dim0 = np1.Shape.ToArray(); int[] dim1 = np2.Shape.ToArray(); int iterator = np1.Shape[1]; prod.Shape = new int[] { dim0[0], dim1[1] }; switch (dataType.Name) { case ("Double"): prod.Data = MatrixMultiplication.MatrixMultiplyDoubleMatrix((double[])np1Dyn, (double[])np2Dyn, dim0, dim1); break; case ("Float"): prod.Data = MatrixMultiplication.MatrixMultiplyfloatMatrix((float[])np1Dyn, (float[])np2Dyn, dim0, dim1); break; case ("Complex"): prod.Data = MatrixMultiplication.MatrixMultiplyComplexMatrix((Complex[])np1Dyn, (Complex[])np2Dyn, dim0, dim1); break; case ("Quaternion"): prod.Data = MatrixMultiplication.MatrixMultiplyQuaternionMatrix((Quaternion[])np1Dyn, (Quaternion[])np2Dyn, dim0, dim1); break; } break; } } return((NDArray <TData>)prod); }
private static void TestMatMul() { int testCount = 10000; Stopwatch sw = new Stopwatch(); Rational[,] matData = new Rational[3, 3]; matData.AssignAll(ind => new Rational(ind[0] * matData.GetLength(0) + ind[1])); Matrix <Rational> mat1 = new Matrix <Rational>(matData); Matrix <Rational> mat2 = new Matrix <Rational>(mat1.Transposition); Console.WriteLine("Multiplying matrices:"); Console.WriteLine(mat1); Console.WriteLine("And:"); Console.WriteLine(mat2); Console.WriteLine("For " + testCount + " times..."); sw.Start(); Matrix <Rational> res = null; for (int i = 0; i < testCount; i++) { res = mat1 * mat2; } sw.Stop(); Console.WriteLine(res); Console.WriteLine("Measured time: " + sw.Elapsed.TotalMilliseconds + "ms"); Console.WriteLine("Average time per operation: " + sw.Elapsed.TotalMilliseconds / testCount + "ms"); Console.WriteLine(); Console.WriteLine("Now testing with ParallelMultiply:"); sw.Restart(); for (int i = 0; i < testCount; i++) { res = MatrixMultiplication.CpuParallelMultiply(mat1, mat2); } sw.Stop(); Console.WriteLine(res); Console.WriteLine("Measured time: " + sw.Elapsed.TotalMilliseconds + "ms"); Console.WriteLine("Average time per operation: " + sw.Elapsed.TotalMilliseconds / testCount + "ms"); Console.WriteLine(); MatrixMultiplication.GpuMultiply <Rational, GpuRational>(mat1, mat2); // 'Warmup' the gpu Console.WriteLine("Now testing with GPUMultiply:"); sw.Restart(); for (int i = 0; i < testCount; i++) { res = MatrixMultiplication.GpuMultiply <Rational, GpuRational>(mat1, mat2); } sw.Stop(); Console.WriteLine(res); Console.WriteLine("Measured time: " + sw.Elapsed.TotalMilliseconds + "ms"); Console.WriteLine("Average time per operation: " + sw.Elapsed.TotalMilliseconds / testCount + "ms"); Console.WriteLine(); }