Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the provided Mathematica code into C while preserving the original functionality.
RowReduce[{{1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22}}]
#include <stdio.h> #define TALLOC(n,typ) malloc(n*sizeof(typ)) #define EL_Type int typedef struct sMtx { int dim_x, dim_y; EL_Type *m_stor; EL_Type **mtx; } *Matrix, sMatrix; typedef struct sRvec { int dim_x; EL_Type *m_stor; } *RowVec, sRowVec; Matrix NewMatrix( int x_dim, int y_dim ) { int n; Matrix m; m = TALLOC( 1, sMatrix); n = x_dim * y_dim; m->dim_x = x_dim; m->dim_y = y_dim; m->m_stor = TALLOC(n, EL_Type); m->mtx = TALLOC(m->dim_y, EL_Type *); for(n=0; n<y_dim; n++) { m->mtx[n] = m->m_stor+n*x_dim; } return m; } void MtxSetRow(Matrix m, int irow, EL_Type *v) { int ix; EL_Type *mr; mr = m->mtx[irow]; for(ix=0; ix<m->dim_x; ix++) mr[ix] = v[ix]; } Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v) { Matrix m; int iy; m = NewMatrix(x_dim, y_dim); for (iy=0; iy<y_dim; iy++) MtxSetRow(m, iy, v[iy]); return m; } void MtxDisplay( Matrix m ) { int iy, ix; const char *sc; for (iy=0; iy<m->dim_y; iy++) { printf(" "); sc = " "; for (ix=0; ix<m->dim_x; ix++) { printf("%s %3d", sc, m->mtx[iy][ix]); sc = ","; } printf("\n"); } printf("\n"); } void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr) { int ix; EL_Type *drow, *srow; drow = m->mtx[ixrdest]; srow = m->mtx[ixrsrc]; for (ix=0; ix<m->dim_x; ix++) drow[ix] += mplr * srow[ix]; } void MtxSwapRows( Matrix m, int rix1, int rix2) { EL_Type *r1, *r2, temp; int ix; if (rix1 == rix2) return; r1 = m->mtx[rix1]; r2 = m->mtx[rix2]; for (ix=0; ix<m->dim_x; ix++) temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp; } void MtxNormalizeRow( Matrix m, int rix, int lead) { int ix; EL_Type *drow; EL_Type lv; drow = m->mtx[rix]; lv = drow[lead]; for (ix=0; ix<m->dim_x; ix++) drow[ix] /= lv; } #define MtxGet( m, rix, cix ) m->mtx[rix][cix] void MtxToReducedREForm(Matrix m) { int lead; int rix, iix; EL_Type lv; int rowCount = m->dim_y; lead = 0; for (rix=0; rix<rowCount; rix++) { if (lead >= m->dim_x) return; iix = rix; while (0 == MtxGet(m, iix,lead)) { iix++; if (iix == rowCount) { iix = rix; lead++; if (lead == m->dim_x) return; } } MtxSwapRows(m, iix, rix ); MtxNormalizeRow(m, rix, lead ); for (iix=0; iix<rowCount; iix++) { if ( iix != rix ) { lv = MtxGet(m, iix, lead ); MtxMulAndAddRows(m,iix, rix, -lv) ; } } lead++; } } int main() { Matrix m1; static EL_Type r1[] = {1,2,-1,-4}; static EL_Type r2[] = {2,3,-1,-11}; static EL_Type r3[] = {-2,0,-3,22}; static EL_Type *im[] = { r1, r2, r3 }; m1 = InitMatrix( 4,3, im ); printf("Initial\n"); MtxDisplay(m1); MtxToReducedREForm(m1); printf("Reduced R-E form\n"); MtxDisplay(m1); return 0; }
Change the following Mathematica code into C# without altering its purpose.
RowReduce[{{1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22}}]
using System; namespace rref { class Program { static void Main(string[] args) { int[,] matrix = new int[3, 4]{ { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; matrix = rref(matrix); } private static int[,] rref(int[,] matrix) { int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1); for (int r = 0; r < rowCount; r++) { if (columnCount <= lead) break; int i = r; while (matrix[i, lead] == 0) { i++; if (i == rowCount) { i = r; lead++; if (columnCount == lead) { lead--; break; } } } for (int j = 0; j < columnCount; j++) { int temp = matrix[r, j]; matrix[r, j] = matrix[i, j]; matrix[i, j] = temp; } int div = matrix[r, lead]; if(div != 0) for (int j = 0; j < columnCount; j++) matrix[r, j] /= div; for (int j = 0; j < rowCount; j++) { if (j != r) { int sub = matrix[j, lead]; for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]); } } lead++; } return matrix; } } }
Generate an equivalent C++ version of this Mathematica code.
RowReduce[{{1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22}}]
#include <algorithm> #include <cstddef> #include <cassert> template<typename MatrixType> struct matrix_traits { typedef typename MatrixType::index_type index_type; typedef typename MatrixType::value_type value_type; static index_type min_row(MatrixType const& A) { return A.min_row(); } static index_type max_row(MatrixType const& A) { return A.max_row(); } static index_type min_column(MatrixType const& A) { return A.min_column(); } static index_type max_column(MatrixType const& A) { return A.max_column(); } static value_type& element(MatrixType& A, index_type i, index_type k) { return A(i,k); } static value_type element(MatrixType const& A, index_type i, index_type k) { return A(i,k); } }; template<typename T, std::size_t rows, std::size_t columns> struct matrix_traits<T[rows][columns]> { typedef std::size_t index_type; typedef T value_type; static index_type min_row(T const (&)[rows][columns]) { return 0; } static index_type max_row(T const (&)[rows][columns]) { return rows-1; } static index_type min_column(T const (&)[rows][columns]) { return 0; } static index_type max_column(T const (&)[rows][columns]) { return columns-1; } static value_type& element(T (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } static value_type element(T const (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } }; template<typename MatrixType> void swap_rows(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) std::swap(mt.element(A, i, col), mt.element(A, k, col)); } template<typename MatrixType> void divide_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(v != 0); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) /= v; } template<typename MatrixType> void add_multiple_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) += v * mt.element(A, k, col); } template<typename MatrixType> void to_reduced_row_echelon_form(MatrixType& A) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; index_type lead = mt.min_row(A); for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row) { if (lead > mt.max_column(A)) return; index_type i = row; while (mt.element(A, i, lead) == 0) { ++i; if (i > mt.max_row(A)) { i = row; ++lead; if (lead > mt.max_column(A)) return; } } swap_rows(A, i, row); divide_row(A, row, mt.element(A, row, lead)); for (i = mt.min_row(A); i <= mt.max_row(A); ++i) { if (i != row) add_multiple_row(A, i, row, -mt.element(A, i, lead)); } } } #include <iostream> int main() { double M[3][4] = { { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; to_reduced_row_echelon_form(M); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) std::cout << M[i][j] << '\t'; std::cout << "\n"; } return EXIT_SUCCESS; }
Transform the following Mathematica implementation into Java, maintaining the same output and logic.
RowReduce[{{1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22}}]
import java.util.*; import java.lang.Math; import org.apache.commons.math.fraction.Fraction; import org.apache.commons.math.fraction.FractionConversionException; class Matrix { LinkedList<LinkedList<Fraction>> matrix; int numRows; int numCols; static class Coordinate { int row; int col; Coordinate(int r, int c) { row = r; col = c; } public String toString() { return "(" + row + ", " + col + ")"; } } Matrix(double [][] m) { numRows = m.length; numCols = m[0].length; matrix = new LinkedList<LinkedList<Fraction>>(); for (int i = 0; i < numRows; i++) { matrix.add(new LinkedList<Fraction>()); for (int j = 0; j < numCols; j++) { try { matrix.get(i).add(new Fraction(m[i][j])); } catch (FractionConversionException e) { System.err.println("Fraction could not be converted from double by apache commons . . ."); } } } } public void Interchange(Coordinate a, Coordinate b) { LinkedList<Fraction> temp = matrix.get(a.row); matrix.set(a.row, matrix.get(b.row)); matrix.set(b.row, temp); int t = a.row; a.row = b.row; b.row = t; } public void Scale(Coordinate x, Fraction d) { LinkedList<Fraction> row = matrix.get(x.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).multiply(d)); } } public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) { LinkedList<Fraction> row = matrix.get(to.row); LinkedList<Fraction> rowMultiplied = matrix.get(from.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar)))); } } public void RREF() { Coordinate pivot = new Coordinate(0,0); int submatrix = 0; for (int x = 0; x < numCols; x++) { pivot = new Coordinate(pivot.row, x); for (int i = x; i < numCols; i++) { if (isColumnZeroes(pivot) == false) { break; } else { pivot.col = i; } } pivot = findPivot(pivot); if (getCoordinate(pivot).doubleValue() == 0.0) { pivot.row++; continue; } if (pivot.row != submatrix) { Interchange(new Coordinate(submatrix, pivot.col), pivot); } if (getCoordinate(pivot).doubleValue() != 1) { Fraction scalar = getCoordinate(pivot).reciprocal(); Scale(pivot, scalar); } for (int i = pivot.row; i < numRows; i++) { if (i == pivot.row) { continue; } Coordinate belowPivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(belowPivot, pivot, complement); } for (int i = pivot.row; i >= 0; i--) { if (i == pivot.row) { if (getCoordinate(pivot).doubleValue() != 1.0) { Scale(pivot, getCoordinate(pivot).reciprocal()); } continue; } if (i == pivot.row) { continue; } Coordinate abovePivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(abovePivot, pivot, complement); } if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) { break; } submatrix++; pivot.row++; } } public boolean isColumnZeroes(Coordinate a) { for (int i = 0; i < numRows; i++) { if (matrix.get(i).get(a.col).doubleValue() != 0.0) { return false; } } return true; } public boolean isRowZeroes(Coordinate a) { for (int i = 0; i < numCols; i++) { if (matrix.get(a.row).get(i).doubleValue() != 0.0) { return false; } } return true; } public Coordinate findPivot(Coordinate a) { int first_row = a.row; Coordinate pivot = new Coordinate(a.row, a.col); Coordinate current = new Coordinate(a.row, a.col); for (int i = a.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() == 1.0) { Interchange(current, a); } } current.row = a.row; for (int i = current.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() != 0) { pivot.row = i; break; } } return pivot; } public Fraction getCoordinate(Coordinate a) { return matrix.get(a.row).get(a.col); } public String toString() { return matrix.toString().replace("], ", "]\n"); } public static void main (String[] args) { double[][] matrix_1 = { {1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22} }; Matrix x = new Matrix(matrix_1); System.out.println("before\n" + x.toString() + "\n"); x.RREF(); System.out.println("after\n" + x.toString() + "\n"); double matrix_2 [][] = { {2, 0, -1, 0, 0}, {1, 0, 0, -1, 0}, {3, 0, 0, -2, -1}, {0, 1, 0, 0, -2}, {0, 1, -1, 0, 0} }; Matrix y = new Matrix(matrix_2); System.out.println("before\n" + y.toString() + "\n"); y.RREF(); System.out.println("after\n" + y.toString() + "\n"); double matrix_3 [][] = { {1, 2, 3, 4, 3, 1}, {2, 4, 6, 2, 6, 2}, {3, 6, 18, 9, 9, -6}, {4, 8, 12, 10, 12, 4}, {5, 10, 24, 11, 15, -4} }; Matrix z = new Matrix(matrix_3); System.out.println("before\n" + z.toString() + "\n"); z.RREF(); System.out.println("after\n" + z.toString() + "\n"); double matrix_4 [][] = { {0, 1}, {1, 2}, {0,5} }; Matrix a = new Matrix(matrix_4); System.out.println("before\n" + a.toString() + "\n"); a.RREF(); System.out.println("after\n" + a.toString() + "\n"); } }
Write the same code in Python as shown below in Mathematica.
RowReduce[{{1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22}}]
def ToReducedRowEchelonForm( M): if not M: return lead = 0 rowCount = len(M) columnCount = len(M[0]) for r in range(rowCount): if lead >= columnCount: return i = r while M[i][lead] == 0: i += 1 if i == rowCount: i = r lead += 1 if columnCount == lead: return M[i],M[r] = M[r],M[i] lv = M[r][lead] M[r] = [ mrx / float(lv) for mrx in M[r]] for i in range(rowCount): if i != r: lv = M[i][lead] M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])] lead += 1 mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22],] ToReducedRowEchelonForm( mtx ) for rw in mtx: print ', '.join( (str(rv) for rv in rw) )
Can you help me rewrite this code in VB instead of Mathematica, keeping it the same logically?
RowReduce[{{1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22}}]
Private Function ToReducedRowEchelonForm(M As Variant) As Variant Dim lead As Integer: lead = 0 Dim rowCount As Integer: rowCount = UBound(M) Dim columnCount As Integer: columnCount = UBound(M(0)) Dim i As Integer For r = 0 To rowCount If lead >= columnCount Then Exit For End If i = r Do While M(i)(lead) = 0 i = i + 1 If i = rowCount Then i = r lead = lead + 1 If lead = columnCount Then Exit For End If End If Loop Dim tmp As Variant tmp = M(r) M(r) = M(i) M(i) = tmp If M(r)(lead) <> 0 Then div = M(r)(lead) For t = LBound(M(r)) To UBound(M(r)) M(r)(t) = M(r)(t) / div Next t End If For j = 0 To rowCount If j <> r Then subt = M(j)(lead) For t = LBound(M(j)) To UBound(M(j)) M(j)(t) = M(j)(t) - subt * M(r)(t) Next t End If Next j lead = lead + 1 Next r ToReducedRowEchelonForm = M End Function Public Sub main() r = ToReducedRowEchelonForm(Array( _ Array(1, 2, -1, -4), _ Array(2, 3, -1, -11), _ Array(-2, 0, -3, 22))) For i = LBound(r) To UBound(r) Debug.Print Join(r(i), vbTab) Next i End Sub
Rewrite the snippet below in Go so it works the same as the original Mathematica code.
RowReduce[{{1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22}}]
package main import "fmt" type matrix [][]float64 func (m matrix) print() { for _, r := range m { fmt.Println(r) } fmt.Println("") } func main() { m := matrix{ { 1, 2, -1, -4}, { 2, 3, -1, -11}, {-2, 0, -3, 22}, } m.print() rref(m) m.print() } func rref(m matrix) { lead := 0 rowCount := len(m) columnCount := len(m[0]) for r := 0; r < rowCount; r++ { if lead >= columnCount { return } i := r for m[i][lead] == 0 { i++ if rowCount == i { i = r lead++ if columnCount == lead { return } } } m[i], m[r] = m[r], m[i] f := 1 / m[r][lead] for j, _ := range m[r] { m[r][j] *= f } for i = 0; i < rowCount; i++ { if i != r { f = m[i][lead] for j, e := range m[r] { m[i][j] -= e * f } } } lead++ } }
Write a version of this MATLAB function in C with identical behavior.
rref([1, 2, -1, -4; 2, 3, -1, -11; -2, 0, -3, 22])
#include <stdio.h> #define TALLOC(n,typ) malloc(n*sizeof(typ)) #define EL_Type int typedef struct sMtx { int dim_x, dim_y; EL_Type *m_stor; EL_Type **mtx; } *Matrix, sMatrix; typedef struct sRvec { int dim_x; EL_Type *m_stor; } *RowVec, sRowVec; Matrix NewMatrix( int x_dim, int y_dim ) { int n; Matrix m; m = TALLOC( 1, sMatrix); n = x_dim * y_dim; m->dim_x = x_dim; m->dim_y = y_dim; m->m_stor = TALLOC(n, EL_Type); m->mtx = TALLOC(m->dim_y, EL_Type *); for(n=0; n<y_dim; n++) { m->mtx[n] = m->m_stor+n*x_dim; } return m; } void MtxSetRow(Matrix m, int irow, EL_Type *v) { int ix; EL_Type *mr; mr = m->mtx[irow]; for(ix=0; ix<m->dim_x; ix++) mr[ix] = v[ix]; } Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v) { Matrix m; int iy; m = NewMatrix(x_dim, y_dim); for (iy=0; iy<y_dim; iy++) MtxSetRow(m, iy, v[iy]); return m; } void MtxDisplay( Matrix m ) { int iy, ix; const char *sc; for (iy=0; iy<m->dim_y; iy++) { printf(" "); sc = " "; for (ix=0; ix<m->dim_x; ix++) { printf("%s %3d", sc, m->mtx[iy][ix]); sc = ","; } printf("\n"); } printf("\n"); } void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr) { int ix; EL_Type *drow, *srow; drow = m->mtx[ixrdest]; srow = m->mtx[ixrsrc]; for (ix=0; ix<m->dim_x; ix++) drow[ix] += mplr * srow[ix]; } void MtxSwapRows( Matrix m, int rix1, int rix2) { EL_Type *r1, *r2, temp; int ix; if (rix1 == rix2) return; r1 = m->mtx[rix1]; r2 = m->mtx[rix2]; for (ix=0; ix<m->dim_x; ix++) temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp; } void MtxNormalizeRow( Matrix m, int rix, int lead) { int ix; EL_Type *drow; EL_Type lv; drow = m->mtx[rix]; lv = drow[lead]; for (ix=0; ix<m->dim_x; ix++) drow[ix] /= lv; } #define MtxGet( m, rix, cix ) m->mtx[rix][cix] void MtxToReducedREForm(Matrix m) { int lead; int rix, iix; EL_Type lv; int rowCount = m->dim_y; lead = 0; for (rix=0; rix<rowCount; rix++) { if (lead >= m->dim_x) return; iix = rix; while (0 == MtxGet(m, iix,lead)) { iix++; if (iix == rowCount) { iix = rix; lead++; if (lead == m->dim_x) return; } } MtxSwapRows(m, iix, rix ); MtxNormalizeRow(m, rix, lead ); for (iix=0; iix<rowCount; iix++) { if ( iix != rix ) { lv = MtxGet(m, iix, lead ); MtxMulAndAddRows(m,iix, rix, -lv) ; } } lead++; } } int main() { Matrix m1; static EL_Type r1[] = {1,2,-1,-4}; static EL_Type r2[] = {2,3,-1,-11}; static EL_Type r3[] = {-2,0,-3,22}; static EL_Type *im[] = { r1, r2, r3 }; m1 = InitMatrix( 4,3, im ); printf("Initial\n"); MtxDisplay(m1); MtxToReducedREForm(m1); printf("Reduced R-E form\n"); MtxDisplay(m1); return 0; }
Write the same algorithm in C# as shown in this MATLAB implementation.
rref([1, 2, -1, -4; 2, 3, -1, -11; -2, 0, -3, 22])
using System; namespace rref { class Program { static void Main(string[] args) { int[,] matrix = new int[3, 4]{ { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; matrix = rref(matrix); } private static int[,] rref(int[,] matrix) { int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1); for (int r = 0; r < rowCount; r++) { if (columnCount <= lead) break; int i = r; while (matrix[i, lead] == 0) { i++; if (i == rowCount) { i = r; lead++; if (columnCount == lead) { lead--; break; } } } for (int j = 0; j < columnCount; j++) { int temp = matrix[r, j]; matrix[r, j] = matrix[i, j]; matrix[i, j] = temp; } int div = matrix[r, lead]; if(div != 0) for (int j = 0; j < columnCount; j++) matrix[r, j] /= div; for (int j = 0; j < rowCount; j++) { if (j != r) { int sub = matrix[j, lead]; for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]); } } lead++; } return matrix; } } }
Maintain the same structure and functionality when rewriting this code in C++.
rref([1, 2, -1, -4; 2, 3, -1, -11; -2, 0, -3, 22])
#include <algorithm> #include <cstddef> #include <cassert> template<typename MatrixType> struct matrix_traits { typedef typename MatrixType::index_type index_type; typedef typename MatrixType::value_type value_type; static index_type min_row(MatrixType const& A) { return A.min_row(); } static index_type max_row(MatrixType const& A) { return A.max_row(); } static index_type min_column(MatrixType const& A) { return A.min_column(); } static index_type max_column(MatrixType const& A) { return A.max_column(); } static value_type& element(MatrixType& A, index_type i, index_type k) { return A(i,k); } static value_type element(MatrixType const& A, index_type i, index_type k) { return A(i,k); } }; template<typename T, std::size_t rows, std::size_t columns> struct matrix_traits<T[rows][columns]> { typedef std::size_t index_type; typedef T value_type; static index_type min_row(T const (&)[rows][columns]) { return 0; } static index_type max_row(T const (&)[rows][columns]) { return rows-1; } static index_type min_column(T const (&)[rows][columns]) { return 0; } static index_type max_column(T const (&)[rows][columns]) { return columns-1; } static value_type& element(T (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } static value_type element(T const (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } }; template<typename MatrixType> void swap_rows(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) std::swap(mt.element(A, i, col), mt.element(A, k, col)); } template<typename MatrixType> void divide_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(v != 0); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) /= v; } template<typename MatrixType> void add_multiple_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) += v * mt.element(A, k, col); } template<typename MatrixType> void to_reduced_row_echelon_form(MatrixType& A) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; index_type lead = mt.min_row(A); for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row) { if (lead > mt.max_column(A)) return; index_type i = row; while (mt.element(A, i, lead) == 0) { ++i; if (i > mt.max_row(A)) { i = row; ++lead; if (lead > mt.max_column(A)) return; } } swap_rows(A, i, row); divide_row(A, row, mt.element(A, row, lead)); for (i = mt.min_row(A); i <= mt.max_row(A); ++i) { if (i != row) add_multiple_row(A, i, row, -mt.element(A, i, lead)); } } } #include <iostream> int main() { double M[3][4] = { { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; to_reduced_row_echelon_form(M); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) std::cout << M[i][j] << '\t'; std::cout << "\n"; } return EXIT_SUCCESS; }
Convert the following code from MATLAB to Java, ensuring the logic remains intact.
rref([1, 2, -1, -4; 2, 3, -1, -11; -2, 0, -3, 22])
import java.util.*; import java.lang.Math; import org.apache.commons.math.fraction.Fraction; import org.apache.commons.math.fraction.FractionConversionException; class Matrix { LinkedList<LinkedList<Fraction>> matrix; int numRows; int numCols; static class Coordinate { int row; int col; Coordinate(int r, int c) { row = r; col = c; } public String toString() { return "(" + row + ", " + col + ")"; } } Matrix(double [][] m) { numRows = m.length; numCols = m[0].length; matrix = new LinkedList<LinkedList<Fraction>>(); for (int i = 0; i < numRows; i++) { matrix.add(new LinkedList<Fraction>()); for (int j = 0; j < numCols; j++) { try { matrix.get(i).add(new Fraction(m[i][j])); } catch (FractionConversionException e) { System.err.println("Fraction could not be converted from double by apache commons . . ."); } } } } public void Interchange(Coordinate a, Coordinate b) { LinkedList<Fraction> temp = matrix.get(a.row); matrix.set(a.row, matrix.get(b.row)); matrix.set(b.row, temp); int t = a.row; a.row = b.row; b.row = t; } public void Scale(Coordinate x, Fraction d) { LinkedList<Fraction> row = matrix.get(x.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).multiply(d)); } } public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) { LinkedList<Fraction> row = matrix.get(to.row); LinkedList<Fraction> rowMultiplied = matrix.get(from.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar)))); } } public void RREF() { Coordinate pivot = new Coordinate(0,0); int submatrix = 0; for (int x = 0; x < numCols; x++) { pivot = new Coordinate(pivot.row, x); for (int i = x; i < numCols; i++) { if (isColumnZeroes(pivot) == false) { break; } else { pivot.col = i; } } pivot = findPivot(pivot); if (getCoordinate(pivot).doubleValue() == 0.0) { pivot.row++; continue; } if (pivot.row != submatrix) { Interchange(new Coordinate(submatrix, pivot.col), pivot); } if (getCoordinate(pivot).doubleValue() != 1) { Fraction scalar = getCoordinate(pivot).reciprocal(); Scale(pivot, scalar); } for (int i = pivot.row; i < numRows; i++) { if (i == pivot.row) { continue; } Coordinate belowPivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(belowPivot, pivot, complement); } for (int i = pivot.row; i >= 0; i--) { if (i == pivot.row) { if (getCoordinate(pivot).doubleValue() != 1.0) { Scale(pivot, getCoordinate(pivot).reciprocal()); } continue; } if (i == pivot.row) { continue; } Coordinate abovePivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(abovePivot, pivot, complement); } if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) { break; } submatrix++; pivot.row++; } } public boolean isColumnZeroes(Coordinate a) { for (int i = 0; i < numRows; i++) { if (matrix.get(i).get(a.col).doubleValue() != 0.0) { return false; } } return true; } public boolean isRowZeroes(Coordinate a) { for (int i = 0; i < numCols; i++) { if (matrix.get(a.row).get(i).doubleValue() != 0.0) { return false; } } return true; } public Coordinate findPivot(Coordinate a) { int first_row = a.row; Coordinate pivot = new Coordinate(a.row, a.col); Coordinate current = new Coordinate(a.row, a.col); for (int i = a.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() == 1.0) { Interchange(current, a); } } current.row = a.row; for (int i = current.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() != 0) { pivot.row = i; break; } } return pivot; } public Fraction getCoordinate(Coordinate a) { return matrix.get(a.row).get(a.col); } public String toString() { return matrix.toString().replace("], ", "]\n"); } public static void main (String[] args) { double[][] matrix_1 = { {1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22} }; Matrix x = new Matrix(matrix_1); System.out.println("before\n" + x.toString() + "\n"); x.RREF(); System.out.println("after\n" + x.toString() + "\n"); double matrix_2 [][] = { {2, 0, -1, 0, 0}, {1, 0, 0, -1, 0}, {3, 0, 0, -2, -1}, {0, 1, 0, 0, -2}, {0, 1, -1, 0, 0} }; Matrix y = new Matrix(matrix_2); System.out.println("before\n" + y.toString() + "\n"); y.RREF(); System.out.println("after\n" + y.toString() + "\n"); double matrix_3 [][] = { {1, 2, 3, 4, 3, 1}, {2, 4, 6, 2, 6, 2}, {3, 6, 18, 9, 9, -6}, {4, 8, 12, 10, 12, 4}, {5, 10, 24, 11, 15, -4} }; Matrix z = new Matrix(matrix_3); System.out.println("before\n" + z.toString() + "\n"); z.RREF(); System.out.println("after\n" + z.toString() + "\n"); double matrix_4 [][] = { {0, 1}, {1, 2}, {0,5} }; Matrix a = new Matrix(matrix_4); System.out.println("before\n" + a.toString() + "\n"); a.RREF(); System.out.println("after\n" + a.toString() + "\n"); } }
Translate this program into Python but keep the logic exactly as in MATLAB.
rref([1, 2, -1, -4; 2, 3, -1, -11; -2, 0, -3, 22])
def ToReducedRowEchelonForm( M): if not M: return lead = 0 rowCount = len(M) columnCount = len(M[0]) for r in range(rowCount): if lead >= columnCount: return i = r while M[i][lead] == 0: i += 1 if i == rowCount: i = r lead += 1 if columnCount == lead: return M[i],M[r] = M[r],M[i] lv = M[r][lead] M[r] = [ mrx / float(lv) for mrx in M[r]] for i in range(rowCount): if i != r: lv = M[i][lead] M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])] lead += 1 mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22],] ToReducedRowEchelonForm( mtx ) for rw in mtx: print ', '.join( (str(rv) for rv in rw) )
Change the following MATLAB code into VB without altering its purpose.
rref([1, 2, -1, -4; 2, 3, -1, -11; -2, 0, -3, 22])
Private Function ToReducedRowEchelonForm(M As Variant) As Variant Dim lead As Integer: lead = 0 Dim rowCount As Integer: rowCount = UBound(M) Dim columnCount As Integer: columnCount = UBound(M(0)) Dim i As Integer For r = 0 To rowCount If lead >= columnCount Then Exit For End If i = r Do While M(i)(lead) = 0 i = i + 1 If i = rowCount Then i = r lead = lead + 1 If lead = columnCount Then Exit For End If End If Loop Dim tmp As Variant tmp = M(r) M(r) = M(i) M(i) = tmp If M(r)(lead) <> 0 Then div = M(r)(lead) For t = LBound(M(r)) To UBound(M(r)) M(r)(t) = M(r)(t) / div Next t End If For j = 0 To rowCount If j <> r Then subt = M(j)(lead) For t = LBound(M(j)) To UBound(M(j)) M(j)(t) = M(j)(t) - subt * M(r)(t) Next t End If Next j lead = lead + 1 Next r ToReducedRowEchelonForm = M End Function Public Sub main() r = ToReducedRowEchelonForm(Array( _ Array(1, 2, -1, -4), _ Array(2, 3, -1, -11), _ Array(-2, 0, -3, 22))) For i = LBound(r) To UBound(r) Debug.Print Join(r(i), vbTab) Next i End Sub
Generate a Go translation of this MATLAB snippet without changing its computational steps.
rref([1, 2, -1, -4; 2, 3, -1, -11; -2, 0, -3, 22])
package main import "fmt" type matrix [][]float64 func (m matrix) print() { for _, r := range m { fmt.Println(r) } fmt.Println("") } func main() { m := matrix{ { 1, 2, -1, -4}, { 2, 3, -1, -11}, {-2, 0, -3, 22}, } m.print() rref(m) m.print() } func rref(m matrix) { lead := 0 rowCount := len(m) columnCount := len(m[0]) for r := 0; r < rowCount; r++ { if lead >= columnCount { return } i := r for m[i][lead] == 0 { i++ if rowCount == i { i = r lead++ if columnCount == lead { return } } } m[i], m[r] = m[r], m[i] f := 1 / m[r][lead] for j, _ := range m[r] { m[r][j] *= f } for i = 0; i < rowCount; i++ { if i != r { f = m[i][lead] for j, e := range m[r] { m[i][j] -= e * f } } } lead++ } }
Transform the following Nim implementation into C, maintaining the same output and logic.
import rationals, strutils type Fraction = Rational[int] const Zero: Fraction = 0 // 1 type Matrix[M, N: static Positive] = array[M, array[N, Fraction]] func toMatrix[M, N: static Positive](a: array[M, array[N, int]]): Matrix[M, N] = for i in 0..<M: for j in 0..<N: result[i][j] = a[i][j] // 1 func transformToRref(mat: var Matrix) = var lead = 0 for r in 0..<mat.M: if lead >= mat.N: return var i = r while mat[i][lead] == Zero: inc i if i == mat.M: i = r inc lead if lead == mat.N: return swap mat[i], mat[r] if (let d = mat[r][lead]; d) != Zero: for item in mat[r].mitems: item /= d for i in 0..<mat.M: if i != r: let m = mat[i][lead] for c in 0..<mat.N: mat[i][c] -= mat[r][c] * m inc lead proc `$`(mat: Matrix): string = for row in mat: var line = "" for val in row: line.addSep(" ", 0) line.add val.toFloat.formatFloat(ffDecimal, 2).align(7) echo line template runTest(mat: Matrix) = echo "Original matrix:" echo mat echo "Reduced row echelon form:" mat.transformToRref() echo mat echo "" var m1 = [[ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22]].toMatrix() var m2 = [[2, 0, -1, 0, 0], [1, 0, 0, -1, 0], [3, 0, 0, -2, -1], [0, 1, 0, 0, -2], [0, 1, -1, 0, 0]].toMatrix() var m3 = [[1, 2, 3, 4, 3, 1], [2, 4, 6, 2, 6, 2], [3, 6, 18, 9, 9, -6], [4, 8, 12, 10, 12, 4], [5, 10, 24, 11, 15, -4]].toMatrix() var m4 = [[0, 1], [1, 2], [0, 5]].toMatrix() runTest(m1) runTest(m2) runTest(m3) runTest(m4)
#include <stdio.h> #define TALLOC(n,typ) malloc(n*sizeof(typ)) #define EL_Type int typedef struct sMtx { int dim_x, dim_y; EL_Type *m_stor; EL_Type **mtx; } *Matrix, sMatrix; typedef struct sRvec { int dim_x; EL_Type *m_stor; } *RowVec, sRowVec; Matrix NewMatrix( int x_dim, int y_dim ) { int n; Matrix m; m = TALLOC( 1, sMatrix); n = x_dim * y_dim; m->dim_x = x_dim; m->dim_y = y_dim; m->m_stor = TALLOC(n, EL_Type); m->mtx = TALLOC(m->dim_y, EL_Type *); for(n=0; n<y_dim; n++) { m->mtx[n] = m->m_stor+n*x_dim; } return m; } void MtxSetRow(Matrix m, int irow, EL_Type *v) { int ix; EL_Type *mr; mr = m->mtx[irow]; for(ix=0; ix<m->dim_x; ix++) mr[ix] = v[ix]; } Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v) { Matrix m; int iy; m = NewMatrix(x_dim, y_dim); for (iy=0; iy<y_dim; iy++) MtxSetRow(m, iy, v[iy]); return m; } void MtxDisplay( Matrix m ) { int iy, ix; const char *sc; for (iy=0; iy<m->dim_y; iy++) { printf(" "); sc = " "; for (ix=0; ix<m->dim_x; ix++) { printf("%s %3d", sc, m->mtx[iy][ix]); sc = ","; } printf("\n"); } printf("\n"); } void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr) { int ix; EL_Type *drow, *srow; drow = m->mtx[ixrdest]; srow = m->mtx[ixrsrc]; for (ix=0; ix<m->dim_x; ix++) drow[ix] += mplr * srow[ix]; } void MtxSwapRows( Matrix m, int rix1, int rix2) { EL_Type *r1, *r2, temp; int ix; if (rix1 == rix2) return; r1 = m->mtx[rix1]; r2 = m->mtx[rix2]; for (ix=0; ix<m->dim_x; ix++) temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp; } void MtxNormalizeRow( Matrix m, int rix, int lead) { int ix; EL_Type *drow; EL_Type lv; drow = m->mtx[rix]; lv = drow[lead]; for (ix=0; ix<m->dim_x; ix++) drow[ix] /= lv; } #define MtxGet( m, rix, cix ) m->mtx[rix][cix] void MtxToReducedREForm(Matrix m) { int lead; int rix, iix; EL_Type lv; int rowCount = m->dim_y; lead = 0; for (rix=0; rix<rowCount; rix++) { if (lead >= m->dim_x) return; iix = rix; while (0 == MtxGet(m, iix,lead)) { iix++; if (iix == rowCount) { iix = rix; lead++; if (lead == m->dim_x) return; } } MtxSwapRows(m, iix, rix ); MtxNormalizeRow(m, rix, lead ); for (iix=0; iix<rowCount; iix++) { if ( iix != rix ) { lv = MtxGet(m, iix, lead ); MtxMulAndAddRows(m,iix, rix, -lv) ; } } lead++; } } int main() { Matrix m1; static EL_Type r1[] = {1,2,-1,-4}; static EL_Type r2[] = {2,3,-1,-11}; static EL_Type r3[] = {-2,0,-3,22}; static EL_Type *im[] = { r1, r2, r3 }; m1 = InitMatrix( 4,3, im ); printf("Initial\n"); MtxDisplay(m1); MtxToReducedREForm(m1); printf("Reduced R-E form\n"); MtxDisplay(m1); return 0; }
Write a version of this Nim function in C# with identical behavior.
import rationals, strutils type Fraction = Rational[int] const Zero: Fraction = 0 // 1 type Matrix[M, N: static Positive] = array[M, array[N, Fraction]] func toMatrix[M, N: static Positive](a: array[M, array[N, int]]): Matrix[M, N] = for i in 0..<M: for j in 0..<N: result[i][j] = a[i][j] // 1 func transformToRref(mat: var Matrix) = var lead = 0 for r in 0..<mat.M: if lead >= mat.N: return var i = r while mat[i][lead] == Zero: inc i if i == mat.M: i = r inc lead if lead == mat.N: return swap mat[i], mat[r] if (let d = mat[r][lead]; d) != Zero: for item in mat[r].mitems: item /= d for i in 0..<mat.M: if i != r: let m = mat[i][lead] for c in 0..<mat.N: mat[i][c] -= mat[r][c] * m inc lead proc `$`(mat: Matrix): string = for row in mat: var line = "" for val in row: line.addSep(" ", 0) line.add val.toFloat.formatFloat(ffDecimal, 2).align(7) echo line template runTest(mat: Matrix) = echo "Original matrix:" echo mat echo "Reduced row echelon form:" mat.transformToRref() echo mat echo "" var m1 = [[ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22]].toMatrix() var m2 = [[2, 0, -1, 0, 0], [1, 0, 0, -1, 0], [3, 0, 0, -2, -1], [0, 1, 0, 0, -2], [0, 1, -1, 0, 0]].toMatrix() var m3 = [[1, 2, 3, 4, 3, 1], [2, 4, 6, 2, 6, 2], [3, 6, 18, 9, 9, -6], [4, 8, 12, 10, 12, 4], [5, 10, 24, 11, 15, -4]].toMatrix() var m4 = [[0, 1], [1, 2], [0, 5]].toMatrix() runTest(m1) runTest(m2) runTest(m3) runTest(m4)
using System; namespace rref { class Program { static void Main(string[] args) { int[,] matrix = new int[3, 4]{ { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; matrix = rref(matrix); } private static int[,] rref(int[,] matrix) { int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1); for (int r = 0; r < rowCount; r++) { if (columnCount <= lead) break; int i = r; while (matrix[i, lead] == 0) { i++; if (i == rowCount) { i = r; lead++; if (columnCount == lead) { lead--; break; } } } for (int j = 0; j < columnCount; j++) { int temp = matrix[r, j]; matrix[r, j] = matrix[i, j]; matrix[i, j] = temp; } int div = matrix[r, lead]; if(div != 0) for (int j = 0; j < columnCount; j++) matrix[r, j] /= div; for (int j = 0; j < rowCount; j++) { if (j != r) { int sub = matrix[j, lead]; for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]); } } lead++; } return matrix; } } }
Preserve the algorithm and functionality while converting the code from Nim to C++.
import rationals, strutils type Fraction = Rational[int] const Zero: Fraction = 0 // 1 type Matrix[M, N: static Positive] = array[M, array[N, Fraction]] func toMatrix[M, N: static Positive](a: array[M, array[N, int]]): Matrix[M, N] = for i in 0..<M: for j in 0..<N: result[i][j] = a[i][j] // 1 func transformToRref(mat: var Matrix) = var lead = 0 for r in 0..<mat.M: if lead >= mat.N: return var i = r while mat[i][lead] == Zero: inc i if i == mat.M: i = r inc lead if lead == mat.N: return swap mat[i], mat[r] if (let d = mat[r][lead]; d) != Zero: for item in mat[r].mitems: item /= d for i in 0..<mat.M: if i != r: let m = mat[i][lead] for c in 0..<mat.N: mat[i][c] -= mat[r][c] * m inc lead proc `$`(mat: Matrix): string = for row in mat: var line = "" for val in row: line.addSep(" ", 0) line.add val.toFloat.formatFloat(ffDecimal, 2).align(7) echo line template runTest(mat: Matrix) = echo "Original matrix:" echo mat echo "Reduced row echelon form:" mat.transformToRref() echo mat echo "" var m1 = [[ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22]].toMatrix() var m2 = [[2, 0, -1, 0, 0], [1, 0, 0, -1, 0], [3, 0, 0, -2, -1], [0, 1, 0, 0, -2], [0, 1, -1, 0, 0]].toMatrix() var m3 = [[1, 2, 3, 4, 3, 1], [2, 4, 6, 2, 6, 2], [3, 6, 18, 9, 9, -6], [4, 8, 12, 10, 12, 4], [5, 10, 24, 11, 15, -4]].toMatrix() var m4 = [[0, 1], [1, 2], [0, 5]].toMatrix() runTest(m1) runTest(m2) runTest(m3) runTest(m4)
#include <algorithm> #include <cstddef> #include <cassert> template<typename MatrixType> struct matrix_traits { typedef typename MatrixType::index_type index_type; typedef typename MatrixType::value_type value_type; static index_type min_row(MatrixType const& A) { return A.min_row(); } static index_type max_row(MatrixType const& A) { return A.max_row(); } static index_type min_column(MatrixType const& A) { return A.min_column(); } static index_type max_column(MatrixType const& A) { return A.max_column(); } static value_type& element(MatrixType& A, index_type i, index_type k) { return A(i,k); } static value_type element(MatrixType const& A, index_type i, index_type k) { return A(i,k); } }; template<typename T, std::size_t rows, std::size_t columns> struct matrix_traits<T[rows][columns]> { typedef std::size_t index_type; typedef T value_type; static index_type min_row(T const (&)[rows][columns]) { return 0; } static index_type max_row(T const (&)[rows][columns]) { return rows-1; } static index_type min_column(T const (&)[rows][columns]) { return 0; } static index_type max_column(T const (&)[rows][columns]) { return columns-1; } static value_type& element(T (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } static value_type element(T const (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } }; template<typename MatrixType> void swap_rows(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) std::swap(mt.element(A, i, col), mt.element(A, k, col)); } template<typename MatrixType> void divide_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(v != 0); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) /= v; } template<typename MatrixType> void add_multiple_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) += v * mt.element(A, k, col); } template<typename MatrixType> void to_reduced_row_echelon_form(MatrixType& A) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; index_type lead = mt.min_row(A); for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row) { if (lead > mt.max_column(A)) return; index_type i = row; while (mt.element(A, i, lead) == 0) { ++i; if (i > mt.max_row(A)) { i = row; ++lead; if (lead > mt.max_column(A)) return; } } swap_rows(A, i, row); divide_row(A, row, mt.element(A, row, lead)); for (i = mt.min_row(A); i <= mt.max_row(A); ++i) { if (i != row) add_multiple_row(A, i, row, -mt.element(A, i, lead)); } } } #include <iostream> int main() { double M[3][4] = { { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; to_reduced_row_echelon_form(M); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) std::cout << M[i][j] << '\t'; std::cout << "\n"; } return EXIT_SUCCESS; }
Can you help me rewrite this code in Java instead of Nim, keeping it the same logically?
import rationals, strutils type Fraction = Rational[int] const Zero: Fraction = 0 // 1 type Matrix[M, N: static Positive] = array[M, array[N, Fraction]] func toMatrix[M, N: static Positive](a: array[M, array[N, int]]): Matrix[M, N] = for i in 0..<M: for j in 0..<N: result[i][j] = a[i][j] // 1 func transformToRref(mat: var Matrix) = var lead = 0 for r in 0..<mat.M: if lead >= mat.N: return var i = r while mat[i][lead] == Zero: inc i if i == mat.M: i = r inc lead if lead == mat.N: return swap mat[i], mat[r] if (let d = mat[r][lead]; d) != Zero: for item in mat[r].mitems: item /= d for i in 0..<mat.M: if i != r: let m = mat[i][lead] for c in 0..<mat.N: mat[i][c] -= mat[r][c] * m inc lead proc `$`(mat: Matrix): string = for row in mat: var line = "" for val in row: line.addSep(" ", 0) line.add val.toFloat.formatFloat(ffDecimal, 2).align(7) echo line template runTest(mat: Matrix) = echo "Original matrix:" echo mat echo "Reduced row echelon form:" mat.transformToRref() echo mat echo "" var m1 = [[ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22]].toMatrix() var m2 = [[2, 0, -1, 0, 0], [1, 0, 0, -1, 0], [3, 0, 0, -2, -1], [0, 1, 0, 0, -2], [0, 1, -1, 0, 0]].toMatrix() var m3 = [[1, 2, 3, 4, 3, 1], [2, 4, 6, 2, 6, 2], [3, 6, 18, 9, 9, -6], [4, 8, 12, 10, 12, 4], [5, 10, 24, 11, 15, -4]].toMatrix() var m4 = [[0, 1], [1, 2], [0, 5]].toMatrix() runTest(m1) runTest(m2) runTest(m3) runTest(m4)
import java.util.*; import java.lang.Math; import org.apache.commons.math.fraction.Fraction; import org.apache.commons.math.fraction.FractionConversionException; class Matrix { LinkedList<LinkedList<Fraction>> matrix; int numRows; int numCols; static class Coordinate { int row; int col; Coordinate(int r, int c) { row = r; col = c; } public String toString() { return "(" + row + ", " + col + ")"; } } Matrix(double [][] m) { numRows = m.length; numCols = m[0].length; matrix = new LinkedList<LinkedList<Fraction>>(); for (int i = 0; i < numRows; i++) { matrix.add(new LinkedList<Fraction>()); for (int j = 0; j < numCols; j++) { try { matrix.get(i).add(new Fraction(m[i][j])); } catch (FractionConversionException e) { System.err.println("Fraction could not be converted from double by apache commons . . ."); } } } } public void Interchange(Coordinate a, Coordinate b) { LinkedList<Fraction> temp = matrix.get(a.row); matrix.set(a.row, matrix.get(b.row)); matrix.set(b.row, temp); int t = a.row; a.row = b.row; b.row = t; } public void Scale(Coordinate x, Fraction d) { LinkedList<Fraction> row = matrix.get(x.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).multiply(d)); } } public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) { LinkedList<Fraction> row = matrix.get(to.row); LinkedList<Fraction> rowMultiplied = matrix.get(from.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar)))); } } public void RREF() { Coordinate pivot = new Coordinate(0,0); int submatrix = 0; for (int x = 0; x < numCols; x++) { pivot = new Coordinate(pivot.row, x); for (int i = x; i < numCols; i++) { if (isColumnZeroes(pivot) == false) { break; } else { pivot.col = i; } } pivot = findPivot(pivot); if (getCoordinate(pivot).doubleValue() == 0.0) { pivot.row++; continue; } if (pivot.row != submatrix) { Interchange(new Coordinate(submatrix, pivot.col), pivot); } if (getCoordinate(pivot).doubleValue() != 1) { Fraction scalar = getCoordinate(pivot).reciprocal(); Scale(pivot, scalar); } for (int i = pivot.row; i < numRows; i++) { if (i == pivot.row) { continue; } Coordinate belowPivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(belowPivot, pivot, complement); } for (int i = pivot.row; i >= 0; i--) { if (i == pivot.row) { if (getCoordinate(pivot).doubleValue() != 1.0) { Scale(pivot, getCoordinate(pivot).reciprocal()); } continue; } if (i == pivot.row) { continue; } Coordinate abovePivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(abovePivot, pivot, complement); } if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) { break; } submatrix++; pivot.row++; } } public boolean isColumnZeroes(Coordinate a) { for (int i = 0; i < numRows; i++) { if (matrix.get(i).get(a.col).doubleValue() != 0.0) { return false; } } return true; } public boolean isRowZeroes(Coordinate a) { for (int i = 0; i < numCols; i++) { if (matrix.get(a.row).get(i).doubleValue() != 0.0) { return false; } } return true; } public Coordinate findPivot(Coordinate a) { int first_row = a.row; Coordinate pivot = new Coordinate(a.row, a.col); Coordinate current = new Coordinate(a.row, a.col); for (int i = a.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() == 1.0) { Interchange(current, a); } } current.row = a.row; for (int i = current.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() != 0) { pivot.row = i; break; } } return pivot; } public Fraction getCoordinate(Coordinate a) { return matrix.get(a.row).get(a.col); } public String toString() { return matrix.toString().replace("], ", "]\n"); } public static void main (String[] args) { double[][] matrix_1 = { {1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22} }; Matrix x = new Matrix(matrix_1); System.out.println("before\n" + x.toString() + "\n"); x.RREF(); System.out.println("after\n" + x.toString() + "\n"); double matrix_2 [][] = { {2, 0, -1, 0, 0}, {1, 0, 0, -1, 0}, {3, 0, 0, -2, -1}, {0, 1, 0, 0, -2}, {0, 1, -1, 0, 0} }; Matrix y = new Matrix(matrix_2); System.out.println("before\n" + y.toString() + "\n"); y.RREF(); System.out.println("after\n" + y.toString() + "\n"); double matrix_3 [][] = { {1, 2, 3, 4, 3, 1}, {2, 4, 6, 2, 6, 2}, {3, 6, 18, 9, 9, -6}, {4, 8, 12, 10, 12, 4}, {5, 10, 24, 11, 15, -4} }; Matrix z = new Matrix(matrix_3); System.out.println("before\n" + z.toString() + "\n"); z.RREF(); System.out.println("after\n" + z.toString() + "\n"); double matrix_4 [][] = { {0, 1}, {1, 2}, {0,5} }; Matrix a = new Matrix(matrix_4); System.out.println("before\n" + a.toString() + "\n"); a.RREF(); System.out.println("after\n" + a.toString() + "\n"); } }
Produce a language-to-language conversion: from Nim to Python, same semantics.
import rationals, strutils type Fraction = Rational[int] const Zero: Fraction = 0 // 1 type Matrix[M, N: static Positive] = array[M, array[N, Fraction]] func toMatrix[M, N: static Positive](a: array[M, array[N, int]]): Matrix[M, N] = for i in 0..<M: for j in 0..<N: result[i][j] = a[i][j] // 1 func transformToRref(mat: var Matrix) = var lead = 0 for r in 0..<mat.M: if lead >= mat.N: return var i = r while mat[i][lead] == Zero: inc i if i == mat.M: i = r inc lead if lead == mat.N: return swap mat[i], mat[r] if (let d = mat[r][lead]; d) != Zero: for item in mat[r].mitems: item /= d for i in 0..<mat.M: if i != r: let m = mat[i][lead] for c in 0..<mat.N: mat[i][c] -= mat[r][c] * m inc lead proc `$`(mat: Matrix): string = for row in mat: var line = "" for val in row: line.addSep(" ", 0) line.add val.toFloat.formatFloat(ffDecimal, 2).align(7) echo line template runTest(mat: Matrix) = echo "Original matrix:" echo mat echo "Reduced row echelon form:" mat.transformToRref() echo mat echo "" var m1 = [[ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22]].toMatrix() var m2 = [[2, 0, -1, 0, 0], [1, 0, 0, -1, 0], [3, 0, 0, -2, -1], [0, 1, 0, 0, -2], [0, 1, -1, 0, 0]].toMatrix() var m3 = [[1, 2, 3, 4, 3, 1], [2, 4, 6, 2, 6, 2], [3, 6, 18, 9, 9, -6], [4, 8, 12, 10, 12, 4], [5, 10, 24, 11, 15, -4]].toMatrix() var m4 = [[0, 1], [1, 2], [0, 5]].toMatrix() runTest(m1) runTest(m2) runTest(m3) runTest(m4)
def ToReducedRowEchelonForm( M): if not M: return lead = 0 rowCount = len(M) columnCount = len(M[0]) for r in range(rowCount): if lead >= columnCount: return i = r while M[i][lead] == 0: i += 1 if i == rowCount: i = r lead += 1 if columnCount == lead: return M[i],M[r] = M[r],M[i] lv = M[r][lead] M[r] = [ mrx / float(lv) for mrx in M[r]] for i in range(rowCount): if i != r: lv = M[i][lead] M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])] lead += 1 mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22],] ToReducedRowEchelonForm( mtx ) for rw in mtx: print ', '.join( (str(rv) for rv in rw) )
Produce a language-to-language conversion: from Nim to VB, same semantics.
import rationals, strutils type Fraction = Rational[int] const Zero: Fraction = 0 // 1 type Matrix[M, N: static Positive] = array[M, array[N, Fraction]] func toMatrix[M, N: static Positive](a: array[M, array[N, int]]): Matrix[M, N] = for i in 0..<M: for j in 0..<N: result[i][j] = a[i][j] // 1 func transformToRref(mat: var Matrix) = var lead = 0 for r in 0..<mat.M: if lead >= mat.N: return var i = r while mat[i][lead] == Zero: inc i if i == mat.M: i = r inc lead if lead == mat.N: return swap mat[i], mat[r] if (let d = mat[r][lead]; d) != Zero: for item in mat[r].mitems: item /= d for i in 0..<mat.M: if i != r: let m = mat[i][lead] for c in 0..<mat.N: mat[i][c] -= mat[r][c] * m inc lead proc `$`(mat: Matrix): string = for row in mat: var line = "" for val in row: line.addSep(" ", 0) line.add val.toFloat.formatFloat(ffDecimal, 2).align(7) echo line template runTest(mat: Matrix) = echo "Original matrix:" echo mat echo "Reduced row echelon form:" mat.transformToRref() echo mat echo "" var m1 = [[ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22]].toMatrix() var m2 = [[2, 0, -1, 0, 0], [1, 0, 0, -1, 0], [3, 0, 0, -2, -1], [0, 1, 0, 0, -2], [0, 1, -1, 0, 0]].toMatrix() var m3 = [[1, 2, 3, 4, 3, 1], [2, 4, 6, 2, 6, 2], [3, 6, 18, 9, 9, -6], [4, 8, 12, 10, 12, 4], [5, 10, 24, 11, 15, -4]].toMatrix() var m4 = [[0, 1], [1, 2], [0, 5]].toMatrix() runTest(m1) runTest(m2) runTest(m3) runTest(m4)
Private Function ToReducedRowEchelonForm(M As Variant) As Variant Dim lead As Integer: lead = 0 Dim rowCount As Integer: rowCount = UBound(M) Dim columnCount As Integer: columnCount = UBound(M(0)) Dim i As Integer For r = 0 To rowCount If lead >= columnCount Then Exit For End If i = r Do While M(i)(lead) = 0 i = i + 1 If i = rowCount Then i = r lead = lead + 1 If lead = columnCount Then Exit For End If End If Loop Dim tmp As Variant tmp = M(r) M(r) = M(i) M(i) = tmp If M(r)(lead) <> 0 Then div = M(r)(lead) For t = LBound(M(r)) To UBound(M(r)) M(r)(t) = M(r)(t) / div Next t End If For j = 0 To rowCount If j <> r Then subt = M(j)(lead) For t = LBound(M(j)) To UBound(M(j)) M(j)(t) = M(j)(t) - subt * M(r)(t) Next t End If Next j lead = lead + 1 Next r ToReducedRowEchelonForm = M End Function Public Sub main() r = ToReducedRowEchelonForm(Array( _ Array(1, 2, -1, -4), _ Array(2, 3, -1, -11), _ Array(-2, 0, -3, 22))) For i = LBound(r) To UBound(r) Debug.Print Join(r(i), vbTab) Next i End Sub
Port the following code from Nim to Go with equivalent syntax and logic.
import rationals, strutils type Fraction = Rational[int] const Zero: Fraction = 0 // 1 type Matrix[M, N: static Positive] = array[M, array[N, Fraction]] func toMatrix[M, N: static Positive](a: array[M, array[N, int]]): Matrix[M, N] = for i in 0..<M: for j in 0..<N: result[i][j] = a[i][j] // 1 func transformToRref(mat: var Matrix) = var lead = 0 for r in 0..<mat.M: if lead >= mat.N: return var i = r while mat[i][lead] == Zero: inc i if i == mat.M: i = r inc lead if lead == mat.N: return swap mat[i], mat[r] if (let d = mat[r][lead]; d) != Zero: for item in mat[r].mitems: item /= d for i in 0..<mat.M: if i != r: let m = mat[i][lead] for c in 0..<mat.N: mat[i][c] -= mat[r][c] * m inc lead proc `$`(mat: Matrix): string = for row in mat: var line = "" for val in row: line.addSep(" ", 0) line.add val.toFloat.formatFloat(ffDecimal, 2).align(7) echo line template runTest(mat: Matrix) = echo "Original matrix:" echo mat echo "Reduced row echelon form:" mat.transformToRref() echo mat echo "" var m1 = [[ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22]].toMatrix() var m2 = [[2, 0, -1, 0, 0], [1, 0, 0, -1, 0], [3, 0, 0, -2, -1], [0, 1, 0, 0, -2], [0, 1, -1, 0, 0]].toMatrix() var m3 = [[1, 2, 3, 4, 3, 1], [2, 4, 6, 2, 6, 2], [3, 6, 18, 9, 9, -6], [4, 8, 12, 10, 12, 4], [5, 10, 24, 11, 15, -4]].toMatrix() var m4 = [[0, 1], [1, 2], [0, 5]].toMatrix() runTest(m1) runTest(m2) runTest(m3) runTest(m4)
package main import "fmt" type matrix [][]float64 func (m matrix) print() { for _, r := range m { fmt.Println(r) } fmt.Println("") } func main() { m := matrix{ { 1, 2, -1, -4}, { 2, 3, -1, -11}, {-2, 0, -3, 22}, } m.print() rref(m) m.print() } func rref(m matrix) { lead := 0 rowCount := len(m) columnCount := len(m[0]) for r := 0; r < rowCount; r++ { if lead >= columnCount { return } i := r for m[i][lead] == 0 { i++ if rowCount == i { i = r lead++ if columnCount == lead { return } } } m[i], m[r] = m[r], m[i] f := 1 / m[r][lead] for j, _ := range m[r] { m[r][j] *= f } for i = 0; i < rowCount; i++ { if i != r { f = m[i][lead] for j, e := range m[r] { m[i][j] -= e * f } } } lead++ } }
Change the programming language of this snippet from OCaml to C without modifying what it does.
let swap_rows m i j = let tmp = m.(i) in m.(i) <- m.(j); m.(j) <- tmp; ;; let rref m = try let lead = ref 0 and rows = Array.length m and cols = Array.length m.(0) in for r = 0 to pred rows do if cols <= !lead then raise Exit; let i = ref r in while m.(!i).(!lead) = 0 do incr i; if rows = !i then begin i := r; incr lead; if cols = !lead then raise Exit; end done; swap_rows m !i r; let lv = m.(r).(!lead) in m.(r) <- Array.map (fun v -> v / lv) m.(r); for i = 0 to pred rows do if i <> r then let lv = m.(i).(!lead) in m.(i) <- Array.mapi (fun i iv -> iv - lv * m.(r).(i)) m.(i); done; incr lead; done with Exit -> () ;; let () = let m = [| [| 1; 2; -1; -4 |]; [| 2; 3; -1; -11 |]; [| -2; 0; -3; 22 |]; |] in rref m; Array.iter (fun row -> Array.iter (fun v -> Printf.printf " %d" v ) row; print_newline() ) m
#include <stdio.h> #define TALLOC(n,typ) malloc(n*sizeof(typ)) #define EL_Type int typedef struct sMtx { int dim_x, dim_y; EL_Type *m_stor; EL_Type **mtx; } *Matrix, sMatrix; typedef struct sRvec { int dim_x; EL_Type *m_stor; } *RowVec, sRowVec; Matrix NewMatrix( int x_dim, int y_dim ) { int n; Matrix m; m = TALLOC( 1, sMatrix); n = x_dim * y_dim; m->dim_x = x_dim; m->dim_y = y_dim; m->m_stor = TALLOC(n, EL_Type); m->mtx = TALLOC(m->dim_y, EL_Type *); for(n=0; n<y_dim; n++) { m->mtx[n] = m->m_stor+n*x_dim; } return m; } void MtxSetRow(Matrix m, int irow, EL_Type *v) { int ix; EL_Type *mr; mr = m->mtx[irow]; for(ix=0; ix<m->dim_x; ix++) mr[ix] = v[ix]; } Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v) { Matrix m; int iy; m = NewMatrix(x_dim, y_dim); for (iy=0; iy<y_dim; iy++) MtxSetRow(m, iy, v[iy]); return m; } void MtxDisplay( Matrix m ) { int iy, ix; const char *sc; for (iy=0; iy<m->dim_y; iy++) { printf(" "); sc = " "; for (ix=0; ix<m->dim_x; ix++) { printf("%s %3d", sc, m->mtx[iy][ix]); sc = ","; } printf("\n"); } printf("\n"); } void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr) { int ix; EL_Type *drow, *srow; drow = m->mtx[ixrdest]; srow = m->mtx[ixrsrc]; for (ix=0; ix<m->dim_x; ix++) drow[ix] += mplr * srow[ix]; } void MtxSwapRows( Matrix m, int rix1, int rix2) { EL_Type *r1, *r2, temp; int ix; if (rix1 == rix2) return; r1 = m->mtx[rix1]; r2 = m->mtx[rix2]; for (ix=0; ix<m->dim_x; ix++) temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp; } void MtxNormalizeRow( Matrix m, int rix, int lead) { int ix; EL_Type *drow; EL_Type lv; drow = m->mtx[rix]; lv = drow[lead]; for (ix=0; ix<m->dim_x; ix++) drow[ix] /= lv; } #define MtxGet( m, rix, cix ) m->mtx[rix][cix] void MtxToReducedREForm(Matrix m) { int lead; int rix, iix; EL_Type lv; int rowCount = m->dim_y; lead = 0; for (rix=0; rix<rowCount; rix++) { if (lead >= m->dim_x) return; iix = rix; while (0 == MtxGet(m, iix,lead)) { iix++; if (iix == rowCount) { iix = rix; lead++; if (lead == m->dim_x) return; } } MtxSwapRows(m, iix, rix ); MtxNormalizeRow(m, rix, lead ); for (iix=0; iix<rowCount; iix++) { if ( iix != rix ) { lv = MtxGet(m, iix, lead ); MtxMulAndAddRows(m,iix, rix, -lv) ; } } lead++; } } int main() { Matrix m1; static EL_Type r1[] = {1,2,-1,-4}; static EL_Type r2[] = {2,3,-1,-11}; static EL_Type r3[] = {-2,0,-3,22}; static EL_Type *im[] = { r1, r2, r3 }; m1 = InitMatrix( 4,3, im ); printf("Initial\n"); MtxDisplay(m1); MtxToReducedREForm(m1); printf("Reduced R-E form\n"); MtxDisplay(m1); return 0; }
Transform the following OCaml implementation into C#, maintaining the same output and logic.
let swap_rows m i j = let tmp = m.(i) in m.(i) <- m.(j); m.(j) <- tmp; ;; let rref m = try let lead = ref 0 and rows = Array.length m and cols = Array.length m.(0) in for r = 0 to pred rows do if cols <= !lead then raise Exit; let i = ref r in while m.(!i).(!lead) = 0 do incr i; if rows = !i then begin i := r; incr lead; if cols = !lead then raise Exit; end done; swap_rows m !i r; let lv = m.(r).(!lead) in m.(r) <- Array.map (fun v -> v / lv) m.(r); for i = 0 to pred rows do if i <> r then let lv = m.(i).(!lead) in m.(i) <- Array.mapi (fun i iv -> iv - lv * m.(r).(i)) m.(i); done; incr lead; done with Exit -> () ;; let () = let m = [| [| 1; 2; -1; -4 |]; [| 2; 3; -1; -11 |]; [| -2; 0; -3; 22 |]; |] in rref m; Array.iter (fun row -> Array.iter (fun v -> Printf.printf " %d" v ) row; print_newline() ) m
using System; namespace rref { class Program { static void Main(string[] args) { int[,] matrix = new int[3, 4]{ { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; matrix = rref(matrix); } private static int[,] rref(int[,] matrix) { int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1); for (int r = 0; r < rowCount; r++) { if (columnCount <= lead) break; int i = r; while (matrix[i, lead] == 0) { i++; if (i == rowCount) { i = r; lead++; if (columnCount == lead) { lead--; break; } } } for (int j = 0; j < columnCount; j++) { int temp = matrix[r, j]; matrix[r, j] = matrix[i, j]; matrix[i, j] = temp; } int div = matrix[r, lead]; if(div != 0) for (int j = 0; j < columnCount; j++) matrix[r, j] /= div; for (int j = 0; j < rowCount; j++) { if (j != r) { int sub = matrix[j, lead]; for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]); } } lead++; } return matrix; } } }
Generate a C++ translation of this OCaml snippet without changing its computational steps.
let swap_rows m i j = let tmp = m.(i) in m.(i) <- m.(j); m.(j) <- tmp; ;; let rref m = try let lead = ref 0 and rows = Array.length m and cols = Array.length m.(0) in for r = 0 to pred rows do if cols <= !lead then raise Exit; let i = ref r in while m.(!i).(!lead) = 0 do incr i; if rows = !i then begin i := r; incr lead; if cols = !lead then raise Exit; end done; swap_rows m !i r; let lv = m.(r).(!lead) in m.(r) <- Array.map (fun v -> v / lv) m.(r); for i = 0 to pred rows do if i <> r then let lv = m.(i).(!lead) in m.(i) <- Array.mapi (fun i iv -> iv - lv * m.(r).(i)) m.(i); done; incr lead; done with Exit -> () ;; let () = let m = [| [| 1; 2; -1; -4 |]; [| 2; 3; -1; -11 |]; [| -2; 0; -3; 22 |]; |] in rref m; Array.iter (fun row -> Array.iter (fun v -> Printf.printf " %d" v ) row; print_newline() ) m
#include <algorithm> #include <cstddef> #include <cassert> template<typename MatrixType> struct matrix_traits { typedef typename MatrixType::index_type index_type; typedef typename MatrixType::value_type value_type; static index_type min_row(MatrixType const& A) { return A.min_row(); } static index_type max_row(MatrixType const& A) { return A.max_row(); } static index_type min_column(MatrixType const& A) { return A.min_column(); } static index_type max_column(MatrixType const& A) { return A.max_column(); } static value_type& element(MatrixType& A, index_type i, index_type k) { return A(i,k); } static value_type element(MatrixType const& A, index_type i, index_type k) { return A(i,k); } }; template<typename T, std::size_t rows, std::size_t columns> struct matrix_traits<T[rows][columns]> { typedef std::size_t index_type; typedef T value_type; static index_type min_row(T const (&)[rows][columns]) { return 0; } static index_type max_row(T const (&)[rows][columns]) { return rows-1; } static index_type min_column(T const (&)[rows][columns]) { return 0; } static index_type max_column(T const (&)[rows][columns]) { return columns-1; } static value_type& element(T (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } static value_type element(T const (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } }; template<typename MatrixType> void swap_rows(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) std::swap(mt.element(A, i, col), mt.element(A, k, col)); } template<typename MatrixType> void divide_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(v != 0); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) /= v; } template<typename MatrixType> void add_multiple_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) += v * mt.element(A, k, col); } template<typename MatrixType> void to_reduced_row_echelon_form(MatrixType& A) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; index_type lead = mt.min_row(A); for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row) { if (lead > mt.max_column(A)) return; index_type i = row; while (mt.element(A, i, lead) == 0) { ++i; if (i > mt.max_row(A)) { i = row; ++lead; if (lead > mt.max_column(A)) return; } } swap_rows(A, i, row); divide_row(A, row, mt.element(A, row, lead)); for (i = mt.min_row(A); i <= mt.max_row(A); ++i) { if (i != row) add_multiple_row(A, i, row, -mt.element(A, i, lead)); } } } #include <iostream> int main() { double M[3][4] = { { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; to_reduced_row_echelon_form(M); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) std::cout << M[i][j] << '\t'; std::cout << "\n"; } return EXIT_SUCCESS; }
Port the provided OCaml code into Java while preserving the original functionality.
let swap_rows m i j = let tmp = m.(i) in m.(i) <- m.(j); m.(j) <- tmp; ;; let rref m = try let lead = ref 0 and rows = Array.length m and cols = Array.length m.(0) in for r = 0 to pred rows do if cols <= !lead then raise Exit; let i = ref r in while m.(!i).(!lead) = 0 do incr i; if rows = !i then begin i := r; incr lead; if cols = !lead then raise Exit; end done; swap_rows m !i r; let lv = m.(r).(!lead) in m.(r) <- Array.map (fun v -> v / lv) m.(r); for i = 0 to pred rows do if i <> r then let lv = m.(i).(!lead) in m.(i) <- Array.mapi (fun i iv -> iv - lv * m.(r).(i)) m.(i); done; incr lead; done with Exit -> () ;; let () = let m = [| [| 1; 2; -1; -4 |]; [| 2; 3; -1; -11 |]; [| -2; 0; -3; 22 |]; |] in rref m; Array.iter (fun row -> Array.iter (fun v -> Printf.printf " %d" v ) row; print_newline() ) m
import java.util.*; import java.lang.Math; import org.apache.commons.math.fraction.Fraction; import org.apache.commons.math.fraction.FractionConversionException; class Matrix { LinkedList<LinkedList<Fraction>> matrix; int numRows; int numCols; static class Coordinate { int row; int col; Coordinate(int r, int c) { row = r; col = c; } public String toString() { return "(" + row + ", " + col + ")"; } } Matrix(double [][] m) { numRows = m.length; numCols = m[0].length; matrix = new LinkedList<LinkedList<Fraction>>(); for (int i = 0; i < numRows; i++) { matrix.add(new LinkedList<Fraction>()); for (int j = 0; j < numCols; j++) { try { matrix.get(i).add(new Fraction(m[i][j])); } catch (FractionConversionException e) { System.err.println("Fraction could not be converted from double by apache commons . . ."); } } } } public void Interchange(Coordinate a, Coordinate b) { LinkedList<Fraction> temp = matrix.get(a.row); matrix.set(a.row, matrix.get(b.row)); matrix.set(b.row, temp); int t = a.row; a.row = b.row; b.row = t; } public void Scale(Coordinate x, Fraction d) { LinkedList<Fraction> row = matrix.get(x.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).multiply(d)); } } public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) { LinkedList<Fraction> row = matrix.get(to.row); LinkedList<Fraction> rowMultiplied = matrix.get(from.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar)))); } } public void RREF() { Coordinate pivot = new Coordinate(0,0); int submatrix = 0; for (int x = 0; x < numCols; x++) { pivot = new Coordinate(pivot.row, x); for (int i = x; i < numCols; i++) { if (isColumnZeroes(pivot) == false) { break; } else { pivot.col = i; } } pivot = findPivot(pivot); if (getCoordinate(pivot).doubleValue() == 0.0) { pivot.row++; continue; } if (pivot.row != submatrix) { Interchange(new Coordinate(submatrix, pivot.col), pivot); } if (getCoordinate(pivot).doubleValue() != 1) { Fraction scalar = getCoordinate(pivot).reciprocal(); Scale(pivot, scalar); } for (int i = pivot.row; i < numRows; i++) { if (i == pivot.row) { continue; } Coordinate belowPivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(belowPivot, pivot, complement); } for (int i = pivot.row; i >= 0; i--) { if (i == pivot.row) { if (getCoordinate(pivot).doubleValue() != 1.0) { Scale(pivot, getCoordinate(pivot).reciprocal()); } continue; } if (i == pivot.row) { continue; } Coordinate abovePivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(abovePivot, pivot, complement); } if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) { break; } submatrix++; pivot.row++; } } public boolean isColumnZeroes(Coordinate a) { for (int i = 0; i < numRows; i++) { if (matrix.get(i).get(a.col).doubleValue() != 0.0) { return false; } } return true; } public boolean isRowZeroes(Coordinate a) { for (int i = 0; i < numCols; i++) { if (matrix.get(a.row).get(i).doubleValue() != 0.0) { return false; } } return true; } public Coordinate findPivot(Coordinate a) { int first_row = a.row; Coordinate pivot = new Coordinate(a.row, a.col); Coordinate current = new Coordinate(a.row, a.col); for (int i = a.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() == 1.0) { Interchange(current, a); } } current.row = a.row; for (int i = current.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() != 0) { pivot.row = i; break; } } return pivot; } public Fraction getCoordinate(Coordinate a) { return matrix.get(a.row).get(a.col); } public String toString() { return matrix.toString().replace("], ", "]\n"); } public static void main (String[] args) { double[][] matrix_1 = { {1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22} }; Matrix x = new Matrix(matrix_1); System.out.println("before\n" + x.toString() + "\n"); x.RREF(); System.out.println("after\n" + x.toString() + "\n"); double matrix_2 [][] = { {2, 0, -1, 0, 0}, {1, 0, 0, -1, 0}, {3, 0, 0, -2, -1}, {0, 1, 0, 0, -2}, {0, 1, -1, 0, 0} }; Matrix y = new Matrix(matrix_2); System.out.println("before\n" + y.toString() + "\n"); y.RREF(); System.out.println("after\n" + y.toString() + "\n"); double matrix_3 [][] = { {1, 2, 3, 4, 3, 1}, {2, 4, 6, 2, 6, 2}, {3, 6, 18, 9, 9, -6}, {4, 8, 12, 10, 12, 4}, {5, 10, 24, 11, 15, -4} }; Matrix z = new Matrix(matrix_3); System.out.println("before\n" + z.toString() + "\n"); z.RREF(); System.out.println("after\n" + z.toString() + "\n"); double matrix_4 [][] = { {0, 1}, {1, 2}, {0,5} }; Matrix a = new Matrix(matrix_4); System.out.println("before\n" + a.toString() + "\n"); a.RREF(); System.out.println("after\n" + a.toString() + "\n"); } }
Write a version of this OCaml function in Python with identical behavior.
let swap_rows m i j = let tmp = m.(i) in m.(i) <- m.(j); m.(j) <- tmp; ;; let rref m = try let lead = ref 0 and rows = Array.length m and cols = Array.length m.(0) in for r = 0 to pred rows do if cols <= !lead then raise Exit; let i = ref r in while m.(!i).(!lead) = 0 do incr i; if rows = !i then begin i := r; incr lead; if cols = !lead then raise Exit; end done; swap_rows m !i r; let lv = m.(r).(!lead) in m.(r) <- Array.map (fun v -> v / lv) m.(r); for i = 0 to pred rows do if i <> r then let lv = m.(i).(!lead) in m.(i) <- Array.mapi (fun i iv -> iv - lv * m.(r).(i)) m.(i); done; incr lead; done with Exit -> () ;; let () = let m = [| [| 1; 2; -1; -4 |]; [| 2; 3; -1; -11 |]; [| -2; 0; -3; 22 |]; |] in rref m; Array.iter (fun row -> Array.iter (fun v -> Printf.printf " %d" v ) row; print_newline() ) m
def ToReducedRowEchelonForm( M): if not M: return lead = 0 rowCount = len(M) columnCount = len(M[0]) for r in range(rowCount): if lead >= columnCount: return i = r while M[i][lead] == 0: i += 1 if i == rowCount: i = r lead += 1 if columnCount == lead: return M[i],M[r] = M[r],M[i] lv = M[r][lead] M[r] = [ mrx / float(lv) for mrx in M[r]] for i in range(rowCount): if i != r: lv = M[i][lead] M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])] lead += 1 mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22],] ToReducedRowEchelonForm( mtx ) for rw in mtx: print ', '.join( (str(rv) for rv in rw) )
Please provide an equivalent version of this OCaml code in VB.
let swap_rows m i j = let tmp = m.(i) in m.(i) <- m.(j); m.(j) <- tmp; ;; let rref m = try let lead = ref 0 and rows = Array.length m and cols = Array.length m.(0) in for r = 0 to pred rows do if cols <= !lead then raise Exit; let i = ref r in while m.(!i).(!lead) = 0 do incr i; if rows = !i then begin i := r; incr lead; if cols = !lead then raise Exit; end done; swap_rows m !i r; let lv = m.(r).(!lead) in m.(r) <- Array.map (fun v -> v / lv) m.(r); for i = 0 to pred rows do if i <> r then let lv = m.(i).(!lead) in m.(i) <- Array.mapi (fun i iv -> iv - lv * m.(r).(i)) m.(i); done; incr lead; done with Exit -> () ;; let () = let m = [| [| 1; 2; -1; -4 |]; [| 2; 3; -1; -11 |]; [| -2; 0; -3; 22 |]; |] in rref m; Array.iter (fun row -> Array.iter (fun v -> Printf.printf " %d" v ) row; print_newline() ) m
Private Function ToReducedRowEchelonForm(M As Variant) As Variant Dim lead As Integer: lead = 0 Dim rowCount As Integer: rowCount = UBound(M) Dim columnCount As Integer: columnCount = UBound(M(0)) Dim i As Integer For r = 0 To rowCount If lead >= columnCount Then Exit For End If i = r Do While M(i)(lead) = 0 i = i + 1 If i = rowCount Then i = r lead = lead + 1 If lead = columnCount Then Exit For End If End If Loop Dim tmp As Variant tmp = M(r) M(r) = M(i) M(i) = tmp If M(r)(lead) <> 0 Then div = M(r)(lead) For t = LBound(M(r)) To UBound(M(r)) M(r)(t) = M(r)(t) / div Next t End If For j = 0 To rowCount If j <> r Then subt = M(j)(lead) For t = LBound(M(j)) To UBound(M(j)) M(j)(t) = M(j)(t) - subt * M(r)(t) Next t End If Next j lead = lead + 1 Next r ToReducedRowEchelonForm = M End Function Public Sub main() r = ToReducedRowEchelonForm(Array( _ Array(1, 2, -1, -4), _ Array(2, 3, -1, -11), _ Array(-2, 0, -3, 22))) For i = LBound(r) To UBound(r) Debug.Print Join(r(i), vbTab) Next i End Sub
Write a version of this OCaml function in Go with identical behavior.
let swap_rows m i j = let tmp = m.(i) in m.(i) <- m.(j); m.(j) <- tmp; ;; let rref m = try let lead = ref 0 and rows = Array.length m and cols = Array.length m.(0) in for r = 0 to pred rows do if cols <= !lead then raise Exit; let i = ref r in while m.(!i).(!lead) = 0 do incr i; if rows = !i then begin i := r; incr lead; if cols = !lead then raise Exit; end done; swap_rows m !i r; let lv = m.(r).(!lead) in m.(r) <- Array.map (fun v -> v / lv) m.(r); for i = 0 to pred rows do if i <> r then let lv = m.(i).(!lead) in m.(i) <- Array.mapi (fun i iv -> iv - lv * m.(r).(i)) m.(i); done; incr lead; done with Exit -> () ;; let () = let m = [| [| 1; 2; -1; -4 |]; [| 2; 3; -1; -11 |]; [| -2; 0; -3; 22 |]; |] in rref m; Array.iter (fun row -> Array.iter (fun v -> Printf.printf " %d" v ) row; print_newline() ) m
package main import "fmt" type matrix [][]float64 func (m matrix) print() { for _, r := range m { fmt.Println(r) } fmt.Println("") } func main() { m := matrix{ { 1, 2, -1, -4}, { 2, 3, -1, -11}, {-2, 0, -3, 22}, } m.print() rref(m) m.print() } func rref(m matrix) { lead := 0 rowCount := len(m) columnCount := len(m[0]) for r := 0; r < rowCount; r++ { if lead >= columnCount { return } i := r for m[i][lead] == 0 { i++ if rowCount == i { i = r lead++ if columnCount == lead { return } } } m[i], m[r] = m[r], m[i] f := 1 / m[r][lead] for j, _ := range m[r] { m[r][j] *= f } for i = 0; i < rowCount; i++ { if i != r { f = m[i][lead] for j, e := range m[r] { m[i][j] -= e * f } } } lead++ } }
Convert this Perl block to C, preserving its control flow and logic.
sub rref {our @m; local *m = shift; @m or return; my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]})); foreach my $r (0 .. $rows - 1) {$lead < $cols or return; my $i = $r; until ($m[$i][$lead]) {++$i == $rows or next; $i = $r; ++$lead == $cols and return;} @m[$i, $r] = @m[$r, $i]; my $lv = $m[$r][$lead]; $_ /= $lv foreach @{ $m[$r] }; my @mr = @{ $m[$r] }; foreach my $i (0 .. $rows - 1) {$i == $r and next; ($lv, my $n) = ($m[$i][$lead], -1); $_ -= $lv * $mr[++$n] foreach @{ $m[$i] };} ++$lead;}} sub display { join("\n" => map join(" " => map(sprintf("%4d", $_), @$_)), @{+shift})."\n" } @m = ( [ 1, 2, -1, -4 ], [ 2, 3, -1, -11 ], [ -2, 0, -3, 22 ] ); rref(\@m); print display(\@m);
#include <stdio.h> #define TALLOC(n,typ) malloc(n*sizeof(typ)) #define EL_Type int typedef struct sMtx { int dim_x, dim_y; EL_Type *m_stor; EL_Type **mtx; } *Matrix, sMatrix; typedef struct sRvec { int dim_x; EL_Type *m_stor; } *RowVec, sRowVec; Matrix NewMatrix( int x_dim, int y_dim ) { int n; Matrix m; m = TALLOC( 1, sMatrix); n = x_dim * y_dim; m->dim_x = x_dim; m->dim_y = y_dim; m->m_stor = TALLOC(n, EL_Type); m->mtx = TALLOC(m->dim_y, EL_Type *); for(n=0; n<y_dim; n++) { m->mtx[n] = m->m_stor+n*x_dim; } return m; } void MtxSetRow(Matrix m, int irow, EL_Type *v) { int ix; EL_Type *mr; mr = m->mtx[irow]; for(ix=0; ix<m->dim_x; ix++) mr[ix] = v[ix]; } Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v) { Matrix m; int iy; m = NewMatrix(x_dim, y_dim); for (iy=0; iy<y_dim; iy++) MtxSetRow(m, iy, v[iy]); return m; } void MtxDisplay( Matrix m ) { int iy, ix; const char *sc; for (iy=0; iy<m->dim_y; iy++) { printf(" "); sc = " "; for (ix=0; ix<m->dim_x; ix++) { printf("%s %3d", sc, m->mtx[iy][ix]); sc = ","; } printf("\n"); } printf("\n"); } void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr) { int ix; EL_Type *drow, *srow; drow = m->mtx[ixrdest]; srow = m->mtx[ixrsrc]; for (ix=0; ix<m->dim_x; ix++) drow[ix] += mplr * srow[ix]; } void MtxSwapRows( Matrix m, int rix1, int rix2) { EL_Type *r1, *r2, temp; int ix; if (rix1 == rix2) return; r1 = m->mtx[rix1]; r2 = m->mtx[rix2]; for (ix=0; ix<m->dim_x; ix++) temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp; } void MtxNormalizeRow( Matrix m, int rix, int lead) { int ix; EL_Type *drow; EL_Type lv; drow = m->mtx[rix]; lv = drow[lead]; for (ix=0; ix<m->dim_x; ix++) drow[ix] /= lv; } #define MtxGet( m, rix, cix ) m->mtx[rix][cix] void MtxToReducedREForm(Matrix m) { int lead; int rix, iix; EL_Type lv; int rowCount = m->dim_y; lead = 0; for (rix=0; rix<rowCount; rix++) { if (lead >= m->dim_x) return; iix = rix; while (0 == MtxGet(m, iix,lead)) { iix++; if (iix == rowCount) { iix = rix; lead++; if (lead == m->dim_x) return; } } MtxSwapRows(m, iix, rix ); MtxNormalizeRow(m, rix, lead ); for (iix=0; iix<rowCount; iix++) { if ( iix != rix ) { lv = MtxGet(m, iix, lead ); MtxMulAndAddRows(m,iix, rix, -lv) ; } } lead++; } } int main() { Matrix m1; static EL_Type r1[] = {1,2,-1,-4}; static EL_Type r2[] = {2,3,-1,-11}; static EL_Type r3[] = {-2,0,-3,22}; static EL_Type *im[] = { r1, r2, r3 }; m1 = InitMatrix( 4,3, im ); printf("Initial\n"); MtxDisplay(m1); MtxToReducedREForm(m1); printf("Reduced R-E form\n"); MtxDisplay(m1); return 0; }
Keep all operations the same but rewrite the snippet in C#.
sub rref {our @m; local *m = shift; @m or return; my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]})); foreach my $r (0 .. $rows - 1) {$lead < $cols or return; my $i = $r; until ($m[$i][$lead]) {++$i == $rows or next; $i = $r; ++$lead == $cols and return;} @m[$i, $r] = @m[$r, $i]; my $lv = $m[$r][$lead]; $_ /= $lv foreach @{ $m[$r] }; my @mr = @{ $m[$r] }; foreach my $i (0 .. $rows - 1) {$i == $r and next; ($lv, my $n) = ($m[$i][$lead], -1); $_ -= $lv * $mr[++$n] foreach @{ $m[$i] };} ++$lead;}} sub display { join("\n" => map join(" " => map(sprintf("%4d", $_), @$_)), @{+shift})."\n" } @m = ( [ 1, 2, -1, -4 ], [ 2, 3, -1, -11 ], [ -2, 0, -3, 22 ] ); rref(\@m); print display(\@m);
using System; namespace rref { class Program { static void Main(string[] args) { int[,] matrix = new int[3, 4]{ { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; matrix = rref(matrix); } private static int[,] rref(int[,] matrix) { int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1); for (int r = 0; r < rowCount; r++) { if (columnCount <= lead) break; int i = r; while (matrix[i, lead] == 0) { i++; if (i == rowCount) { i = r; lead++; if (columnCount == lead) { lead--; break; } } } for (int j = 0; j < columnCount; j++) { int temp = matrix[r, j]; matrix[r, j] = matrix[i, j]; matrix[i, j] = temp; } int div = matrix[r, lead]; if(div != 0) for (int j = 0; j < columnCount; j++) matrix[r, j] /= div; for (int j = 0; j < rowCount; j++) { if (j != r) { int sub = matrix[j, lead]; for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]); } } lead++; } return matrix; } } }
Generate a C++ translation of this Perl snippet without changing its computational steps.
sub rref {our @m; local *m = shift; @m or return; my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]})); foreach my $r (0 .. $rows - 1) {$lead < $cols or return; my $i = $r; until ($m[$i][$lead]) {++$i == $rows or next; $i = $r; ++$lead == $cols and return;} @m[$i, $r] = @m[$r, $i]; my $lv = $m[$r][$lead]; $_ /= $lv foreach @{ $m[$r] }; my @mr = @{ $m[$r] }; foreach my $i (0 .. $rows - 1) {$i == $r and next; ($lv, my $n) = ($m[$i][$lead], -1); $_ -= $lv * $mr[++$n] foreach @{ $m[$i] };} ++$lead;}} sub display { join("\n" => map join(" " => map(sprintf("%4d", $_), @$_)), @{+shift})."\n" } @m = ( [ 1, 2, -1, -4 ], [ 2, 3, -1, -11 ], [ -2, 0, -3, 22 ] ); rref(\@m); print display(\@m);
#include <algorithm> #include <cstddef> #include <cassert> template<typename MatrixType> struct matrix_traits { typedef typename MatrixType::index_type index_type; typedef typename MatrixType::value_type value_type; static index_type min_row(MatrixType const& A) { return A.min_row(); } static index_type max_row(MatrixType const& A) { return A.max_row(); } static index_type min_column(MatrixType const& A) { return A.min_column(); } static index_type max_column(MatrixType const& A) { return A.max_column(); } static value_type& element(MatrixType& A, index_type i, index_type k) { return A(i,k); } static value_type element(MatrixType const& A, index_type i, index_type k) { return A(i,k); } }; template<typename T, std::size_t rows, std::size_t columns> struct matrix_traits<T[rows][columns]> { typedef std::size_t index_type; typedef T value_type; static index_type min_row(T const (&)[rows][columns]) { return 0; } static index_type max_row(T const (&)[rows][columns]) { return rows-1; } static index_type min_column(T const (&)[rows][columns]) { return 0; } static index_type max_column(T const (&)[rows][columns]) { return columns-1; } static value_type& element(T (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } static value_type element(T const (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } }; template<typename MatrixType> void swap_rows(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) std::swap(mt.element(A, i, col), mt.element(A, k, col)); } template<typename MatrixType> void divide_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(v != 0); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) /= v; } template<typename MatrixType> void add_multiple_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) += v * mt.element(A, k, col); } template<typename MatrixType> void to_reduced_row_echelon_form(MatrixType& A) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; index_type lead = mt.min_row(A); for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row) { if (lead > mt.max_column(A)) return; index_type i = row; while (mt.element(A, i, lead) == 0) { ++i; if (i > mt.max_row(A)) { i = row; ++lead; if (lead > mt.max_column(A)) return; } } swap_rows(A, i, row); divide_row(A, row, mt.element(A, row, lead)); for (i = mt.min_row(A); i <= mt.max_row(A); ++i) { if (i != row) add_multiple_row(A, i, row, -mt.element(A, i, lead)); } } } #include <iostream> int main() { double M[3][4] = { { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; to_reduced_row_echelon_form(M); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) std::cout << M[i][j] << '\t'; std::cout << "\n"; } return EXIT_SUCCESS; }
Convert this Perl block to Java, preserving its control flow and logic.
sub rref {our @m; local *m = shift; @m or return; my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]})); foreach my $r (0 .. $rows - 1) {$lead < $cols or return; my $i = $r; until ($m[$i][$lead]) {++$i == $rows or next; $i = $r; ++$lead == $cols and return;} @m[$i, $r] = @m[$r, $i]; my $lv = $m[$r][$lead]; $_ /= $lv foreach @{ $m[$r] }; my @mr = @{ $m[$r] }; foreach my $i (0 .. $rows - 1) {$i == $r and next; ($lv, my $n) = ($m[$i][$lead], -1); $_ -= $lv * $mr[++$n] foreach @{ $m[$i] };} ++$lead;}} sub display { join("\n" => map join(" " => map(sprintf("%4d", $_), @$_)), @{+shift})."\n" } @m = ( [ 1, 2, -1, -4 ], [ 2, 3, -1, -11 ], [ -2, 0, -3, 22 ] ); rref(\@m); print display(\@m);
import java.util.*; import java.lang.Math; import org.apache.commons.math.fraction.Fraction; import org.apache.commons.math.fraction.FractionConversionException; class Matrix { LinkedList<LinkedList<Fraction>> matrix; int numRows; int numCols; static class Coordinate { int row; int col; Coordinate(int r, int c) { row = r; col = c; } public String toString() { return "(" + row + ", " + col + ")"; } } Matrix(double [][] m) { numRows = m.length; numCols = m[0].length; matrix = new LinkedList<LinkedList<Fraction>>(); for (int i = 0; i < numRows; i++) { matrix.add(new LinkedList<Fraction>()); for (int j = 0; j < numCols; j++) { try { matrix.get(i).add(new Fraction(m[i][j])); } catch (FractionConversionException e) { System.err.println("Fraction could not be converted from double by apache commons . . ."); } } } } public void Interchange(Coordinate a, Coordinate b) { LinkedList<Fraction> temp = matrix.get(a.row); matrix.set(a.row, matrix.get(b.row)); matrix.set(b.row, temp); int t = a.row; a.row = b.row; b.row = t; } public void Scale(Coordinate x, Fraction d) { LinkedList<Fraction> row = matrix.get(x.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).multiply(d)); } } public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) { LinkedList<Fraction> row = matrix.get(to.row); LinkedList<Fraction> rowMultiplied = matrix.get(from.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar)))); } } public void RREF() { Coordinate pivot = new Coordinate(0,0); int submatrix = 0; for (int x = 0; x < numCols; x++) { pivot = new Coordinate(pivot.row, x); for (int i = x; i < numCols; i++) { if (isColumnZeroes(pivot) == false) { break; } else { pivot.col = i; } } pivot = findPivot(pivot); if (getCoordinate(pivot).doubleValue() == 0.0) { pivot.row++; continue; } if (pivot.row != submatrix) { Interchange(new Coordinate(submatrix, pivot.col), pivot); } if (getCoordinate(pivot).doubleValue() != 1) { Fraction scalar = getCoordinate(pivot).reciprocal(); Scale(pivot, scalar); } for (int i = pivot.row; i < numRows; i++) { if (i == pivot.row) { continue; } Coordinate belowPivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(belowPivot, pivot, complement); } for (int i = pivot.row; i >= 0; i--) { if (i == pivot.row) { if (getCoordinate(pivot).doubleValue() != 1.0) { Scale(pivot, getCoordinate(pivot).reciprocal()); } continue; } if (i == pivot.row) { continue; } Coordinate abovePivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(abovePivot, pivot, complement); } if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) { break; } submatrix++; pivot.row++; } } public boolean isColumnZeroes(Coordinate a) { for (int i = 0; i < numRows; i++) { if (matrix.get(i).get(a.col).doubleValue() != 0.0) { return false; } } return true; } public boolean isRowZeroes(Coordinate a) { for (int i = 0; i < numCols; i++) { if (matrix.get(a.row).get(i).doubleValue() != 0.0) { return false; } } return true; } public Coordinate findPivot(Coordinate a) { int first_row = a.row; Coordinate pivot = new Coordinate(a.row, a.col); Coordinate current = new Coordinate(a.row, a.col); for (int i = a.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() == 1.0) { Interchange(current, a); } } current.row = a.row; for (int i = current.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() != 0) { pivot.row = i; break; } } return pivot; } public Fraction getCoordinate(Coordinate a) { return matrix.get(a.row).get(a.col); } public String toString() { return matrix.toString().replace("], ", "]\n"); } public static void main (String[] args) { double[][] matrix_1 = { {1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22} }; Matrix x = new Matrix(matrix_1); System.out.println("before\n" + x.toString() + "\n"); x.RREF(); System.out.println("after\n" + x.toString() + "\n"); double matrix_2 [][] = { {2, 0, -1, 0, 0}, {1, 0, 0, -1, 0}, {3, 0, 0, -2, -1}, {0, 1, 0, 0, -2}, {0, 1, -1, 0, 0} }; Matrix y = new Matrix(matrix_2); System.out.println("before\n" + y.toString() + "\n"); y.RREF(); System.out.println("after\n" + y.toString() + "\n"); double matrix_3 [][] = { {1, 2, 3, 4, 3, 1}, {2, 4, 6, 2, 6, 2}, {3, 6, 18, 9, 9, -6}, {4, 8, 12, 10, 12, 4}, {5, 10, 24, 11, 15, -4} }; Matrix z = new Matrix(matrix_3); System.out.println("before\n" + z.toString() + "\n"); z.RREF(); System.out.println("after\n" + z.toString() + "\n"); double matrix_4 [][] = { {0, 1}, {1, 2}, {0,5} }; Matrix a = new Matrix(matrix_4); System.out.println("before\n" + a.toString() + "\n"); a.RREF(); System.out.println("after\n" + a.toString() + "\n"); } }
Port the following code from Perl to Python with equivalent syntax and logic.
sub rref {our @m; local *m = shift; @m or return; my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]})); foreach my $r (0 .. $rows - 1) {$lead < $cols or return; my $i = $r; until ($m[$i][$lead]) {++$i == $rows or next; $i = $r; ++$lead == $cols and return;} @m[$i, $r] = @m[$r, $i]; my $lv = $m[$r][$lead]; $_ /= $lv foreach @{ $m[$r] }; my @mr = @{ $m[$r] }; foreach my $i (0 .. $rows - 1) {$i == $r and next; ($lv, my $n) = ($m[$i][$lead], -1); $_ -= $lv * $mr[++$n] foreach @{ $m[$i] };} ++$lead;}} sub display { join("\n" => map join(" " => map(sprintf("%4d", $_), @$_)), @{+shift})."\n" } @m = ( [ 1, 2, -1, -4 ], [ 2, 3, -1, -11 ], [ -2, 0, -3, 22 ] ); rref(\@m); print display(\@m);
def ToReducedRowEchelonForm( M): if not M: return lead = 0 rowCount = len(M) columnCount = len(M[0]) for r in range(rowCount): if lead >= columnCount: return i = r while M[i][lead] == 0: i += 1 if i == rowCount: i = r lead += 1 if columnCount == lead: return M[i],M[r] = M[r],M[i] lv = M[r][lead] M[r] = [ mrx / float(lv) for mrx in M[r]] for i in range(rowCount): if i != r: lv = M[i][lead] M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])] lead += 1 mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22],] ToReducedRowEchelonForm( mtx ) for rw in mtx: print ', '.join( (str(rv) for rv in rw) )
Write the same code in VB as shown below in Perl.
sub rref {our @m; local *m = shift; @m or return; my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]})); foreach my $r (0 .. $rows - 1) {$lead < $cols or return; my $i = $r; until ($m[$i][$lead]) {++$i == $rows or next; $i = $r; ++$lead == $cols and return;} @m[$i, $r] = @m[$r, $i]; my $lv = $m[$r][$lead]; $_ /= $lv foreach @{ $m[$r] }; my @mr = @{ $m[$r] }; foreach my $i (0 .. $rows - 1) {$i == $r and next; ($lv, my $n) = ($m[$i][$lead], -1); $_ -= $lv * $mr[++$n] foreach @{ $m[$i] };} ++$lead;}} sub display { join("\n" => map join(" " => map(sprintf("%4d", $_), @$_)), @{+shift})."\n" } @m = ( [ 1, 2, -1, -4 ], [ 2, 3, -1, -11 ], [ -2, 0, -3, 22 ] ); rref(\@m); print display(\@m);
Private Function ToReducedRowEchelonForm(M As Variant) As Variant Dim lead As Integer: lead = 0 Dim rowCount As Integer: rowCount = UBound(M) Dim columnCount As Integer: columnCount = UBound(M(0)) Dim i As Integer For r = 0 To rowCount If lead >= columnCount Then Exit For End If i = r Do While M(i)(lead) = 0 i = i + 1 If i = rowCount Then i = r lead = lead + 1 If lead = columnCount Then Exit For End If End If Loop Dim tmp As Variant tmp = M(r) M(r) = M(i) M(i) = tmp If M(r)(lead) <> 0 Then div = M(r)(lead) For t = LBound(M(r)) To UBound(M(r)) M(r)(t) = M(r)(t) / div Next t End If For j = 0 To rowCount If j <> r Then subt = M(j)(lead) For t = LBound(M(j)) To UBound(M(j)) M(j)(t) = M(j)(t) - subt * M(r)(t) Next t End If Next j lead = lead + 1 Next r ToReducedRowEchelonForm = M End Function Public Sub main() r = ToReducedRowEchelonForm(Array( _ Array(1, 2, -1, -4), _ Array(2, 3, -1, -11), _ Array(-2, 0, -3, 22))) For i = LBound(r) To UBound(r) Debug.Print Join(r(i), vbTab) Next i End Sub
Translate this program into Go but keep the logic exactly as in Perl.
sub rref {our @m; local *m = shift; @m or return; my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]})); foreach my $r (0 .. $rows - 1) {$lead < $cols or return; my $i = $r; until ($m[$i][$lead]) {++$i == $rows or next; $i = $r; ++$lead == $cols and return;} @m[$i, $r] = @m[$r, $i]; my $lv = $m[$r][$lead]; $_ /= $lv foreach @{ $m[$r] }; my @mr = @{ $m[$r] }; foreach my $i (0 .. $rows - 1) {$i == $r and next; ($lv, my $n) = ($m[$i][$lead], -1); $_ -= $lv * $mr[++$n] foreach @{ $m[$i] };} ++$lead;}} sub display { join("\n" => map join(" " => map(sprintf("%4d", $_), @$_)), @{+shift})."\n" } @m = ( [ 1, 2, -1, -4 ], [ 2, 3, -1, -11 ], [ -2, 0, -3, 22 ] ); rref(\@m); print display(\@m);
package main import "fmt" type matrix [][]float64 func (m matrix) print() { for _, r := range m { fmt.Println(r) } fmt.Println("") } func main() { m := matrix{ { 1, 2, -1, -4}, { 2, 3, -1, -11}, {-2, 0, -3, 22}, } m.print() rref(m) m.print() } func rref(m matrix) { lead := 0 rowCount := len(m) columnCount := len(m[0]) for r := 0; r < rowCount; r++ { if lead >= columnCount { return } i := r for m[i][lead] == 0 { i++ if rowCount == i { i = r lead++ if columnCount == lead { return } } } m[i], m[r] = m[r], m[i] f := 1 / m[r][lead] for j, _ := range m[r] { m[r][j] *= f } for i = 0; i < rowCount; i++ { if i != r { f = m[i][lead] for j, e := range m[r] { m[i][j] -= e * f } } } lead++ } }
Write the same algorithm in C as shown in this Racket implementation.
#lang racket (require math) (define (reduced-echelon M) (matrix-row-echelon M #t #t)) (reduced-echelon (matrix [[1 2 -1 -4] [2 3 -1 -11] [-2 0 -3 22]]))
#include <stdio.h> #define TALLOC(n,typ) malloc(n*sizeof(typ)) #define EL_Type int typedef struct sMtx { int dim_x, dim_y; EL_Type *m_stor; EL_Type **mtx; } *Matrix, sMatrix; typedef struct sRvec { int dim_x; EL_Type *m_stor; } *RowVec, sRowVec; Matrix NewMatrix( int x_dim, int y_dim ) { int n; Matrix m; m = TALLOC( 1, sMatrix); n = x_dim * y_dim; m->dim_x = x_dim; m->dim_y = y_dim; m->m_stor = TALLOC(n, EL_Type); m->mtx = TALLOC(m->dim_y, EL_Type *); for(n=0; n<y_dim; n++) { m->mtx[n] = m->m_stor+n*x_dim; } return m; } void MtxSetRow(Matrix m, int irow, EL_Type *v) { int ix; EL_Type *mr; mr = m->mtx[irow]; for(ix=0; ix<m->dim_x; ix++) mr[ix] = v[ix]; } Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v) { Matrix m; int iy; m = NewMatrix(x_dim, y_dim); for (iy=0; iy<y_dim; iy++) MtxSetRow(m, iy, v[iy]); return m; } void MtxDisplay( Matrix m ) { int iy, ix; const char *sc; for (iy=0; iy<m->dim_y; iy++) { printf(" "); sc = " "; for (ix=0; ix<m->dim_x; ix++) { printf("%s %3d", sc, m->mtx[iy][ix]); sc = ","; } printf("\n"); } printf("\n"); } void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr) { int ix; EL_Type *drow, *srow; drow = m->mtx[ixrdest]; srow = m->mtx[ixrsrc]; for (ix=0; ix<m->dim_x; ix++) drow[ix] += mplr * srow[ix]; } void MtxSwapRows( Matrix m, int rix1, int rix2) { EL_Type *r1, *r2, temp; int ix; if (rix1 == rix2) return; r1 = m->mtx[rix1]; r2 = m->mtx[rix2]; for (ix=0; ix<m->dim_x; ix++) temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp; } void MtxNormalizeRow( Matrix m, int rix, int lead) { int ix; EL_Type *drow; EL_Type lv; drow = m->mtx[rix]; lv = drow[lead]; for (ix=0; ix<m->dim_x; ix++) drow[ix] /= lv; } #define MtxGet( m, rix, cix ) m->mtx[rix][cix] void MtxToReducedREForm(Matrix m) { int lead; int rix, iix; EL_Type lv; int rowCount = m->dim_y; lead = 0; for (rix=0; rix<rowCount; rix++) { if (lead >= m->dim_x) return; iix = rix; while (0 == MtxGet(m, iix,lead)) { iix++; if (iix == rowCount) { iix = rix; lead++; if (lead == m->dim_x) return; } } MtxSwapRows(m, iix, rix ); MtxNormalizeRow(m, rix, lead ); for (iix=0; iix<rowCount; iix++) { if ( iix != rix ) { lv = MtxGet(m, iix, lead ); MtxMulAndAddRows(m,iix, rix, -lv) ; } } lead++; } } int main() { Matrix m1; static EL_Type r1[] = {1,2,-1,-4}; static EL_Type r2[] = {2,3,-1,-11}; static EL_Type r3[] = {-2,0,-3,22}; static EL_Type *im[] = { r1, r2, r3 }; m1 = InitMatrix( 4,3, im ); printf("Initial\n"); MtxDisplay(m1); MtxToReducedREForm(m1); printf("Reduced R-E form\n"); MtxDisplay(m1); return 0; }
Keep all operations the same but rewrite the snippet in C#.
#lang racket (require math) (define (reduced-echelon M) (matrix-row-echelon M #t #t)) (reduced-echelon (matrix [[1 2 -1 -4] [2 3 -1 -11] [-2 0 -3 22]]))
using System; namespace rref { class Program { static void Main(string[] args) { int[,] matrix = new int[3, 4]{ { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; matrix = rref(matrix); } private static int[,] rref(int[,] matrix) { int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1); for (int r = 0; r < rowCount; r++) { if (columnCount <= lead) break; int i = r; while (matrix[i, lead] == 0) { i++; if (i == rowCount) { i = r; lead++; if (columnCount == lead) { lead--; break; } } } for (int j = 0; j < columnCount; j++) { int temp = matrix[r, j]; matrix[r, j] = matrix[i, j]; matrix[i, j] = temp; } int div = matrix[r, lead]; if(div != 0) for (int j = 0; j < columnCount; j++) matrix[r, j] /= div; for (int j = 0; j < rowCount; j++) { if (j != r) { int sub = matrix[j, lead]; for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]); } } lead++; } return matrix; } } }
Change the programming language of this snippet from Racket to C++ without modifying what it does.
#lang racket (require math) (define (reduced-echelon M) (matrix-row-echelon M #t #t)) (reduced-echelon (matrix [[1 2 -1 -4] [2 3 -1 -11] [-2 0 -3 22]]))
#include <algorithm> #include <cstddef> #include <cassert> template<typename MatrixType> struct matrix_traits { typedef typename MatrixType::index_type index_type; typedef typename MatrixType::value_type value_type; static index_type min_row(MatrixType const& A) { return A.min_row(); } static index_type max_row(MatrixType const& A) { return A.max_row(); } static index_type min_column(MatrixType const& A) { return A.min_column(); } static index_type max_column(MatrixType const& A) { return A.max_column(); } static value_type& element(MatrixType& A, index_type i, index_type k) { return A(i,k); } static value_type element(MatrixType const& A, index_type i, index_type k) { return A(i,k); } }; template<typename T, std::size_t rows, std::size_t columns> struct matrix_traits<T[rows][columns]> { typedef std::size_t index_type; typedef T value_type; static index_type min_row(T const (&)[rows][columns]) { return 0; } static index_type max_row(T const (&)[rows][columns]) { return rows-1; } static index_type min_column(T const (&)[rows][columns]) { return 0; } static index_type max_column(T const (&)[rows][columns]) { return columns-1; } static value_type& element(T (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } static value_type element(T const (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } }; template<typename MatrixType> void swap_rows(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) std::swap(mt.element(A, i, col), mt.element(A, k, col)); } template<typename MatrixType> void divide_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(v != 0); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) /= v; } template<typename MatrixType> void add_multiple_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) += v * mt.element(A, k, col); } template<typename MatrixType> void to_reduced_row_echelon_form(MatrixType& A) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; index_type lead = mt.min_row(A); for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row) { if (lead > mt.max_column(A)) return; index_type i = row; while (mt.element(A, i, lead) == 0) { ++i; if (i > mt.max_row(A)) { i = row; ++lead; if (lead > mt.max_column(A)) return; } } swap_rows(A, i, row); divide_row(A, row, mt.element(A, row, lead)); for (i = mt.min_row(A); i <= mt.max_row(A); ++i) { if (i != row) add_multiple_row(A, i, row, -mt.element(A, i, lead)); } } } #include <iostream> int main() { double M[3][4] = { { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; to_reduced_row_echelon_form(M); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) std::cout << M[i][j] << '\t'; std::cout << "\n"; } return EXIT_SUCCESS; }
Convert the following code from Racket to Java, ensuring the logic remains intact.
#lang racket (require math) (define (reduced-echelon M) (matrix-row-echelon M #t #t)) (reduced-echelon (matrix [[1 2 -1 -4] [2 3 -1 -11] [-2 0 -3 22]]))
import java.util.*; import java.lang.Math; import org.apache.commons.math.fraction.Fraction; import org.apache.commons.math.fraction.FractionConversionException; class Matrix { LinkedList<LinkedList<Fraction>> matrix; int numRows; int numCols; static class Coordinate { int row; int col; Coordinate(int r, int c) { row = r; col = c; } public String toString() { return "(" + row + ", " + col + ")"; } } Matrix(double [][] m) { numRows = m.length; numCols = m[0].length; matrix = new LinkedList<LinkedList<Fraction>>(); for (int i = 0; i < numRows; i++) { matrix.add(new LinkedList<Fraction>()); for (int j = 0; j < numCols; j++) { try { matrix.get(i).add(new Fraction(m[i][j])); } catch (FractionConversionException e) { System.err.println("Fraction could not be converted from double by apache commons . . ."); } } } } public void Interchange(Coordinate a, Coordinate b) { LinkedList<Fraction> temp = matrix.get(a.row); matrix.set(a.row, matrix.get(b.row)); matrix.set(b.row, temp); int t = a.row; a.row = b.row; b.row = t; } public void Scale(Coordinate x, Fraction d) { LinkedList<Fraction> row = matrix.get(x.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).multiply(d)); } } public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) { LinkedList<Fraction> row = matrix.get(to.row); LinkedList<Fraction> rowMultiplied = matrix.get(from.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar)))); } } public void RREF() { Coordinate pivot = new Coordinate(0,0); int submatrix = 0; for (int x = 0; x < numCols; x++) { pivot = new Coordinate(pivot.row, x); for (int i = x; i < numCols; i++) { if (isColumnZeroes(pivot) == false) { break; } else { pivot.col = i; } } pivot = findPivot(pivot); if (getCoordinate(pivot).doubleValue() == 0.0) { pivot.row++; continue; } if (pivot.row != submatrix) { Interchange(new Coordinate(submatrix, pivot.col), pivot); } if (getCoordinate(pivot).doubleValue() != 1) { Fraction scalar = getCoordinate(pivot).reciprocal(); Scale(pivot, scalar); } for (int i = pivot.row; i < numRows; i++) { if (i == pivot.row) { continue; } Coordinate belowPivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(belowPivot, pivot, complement); } for (int i = pivot.row; i >= 0; i--) { if (i == pivot.row) { if (getCoordinate(pivot).doubleValue() != 1.0) { Scale(pivot, getCoordinate(pivot).reciprocal()); } continue; } if (i == pivot.row) { continue; } Coordinate abovePivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(abovePivot, pivot, complement); } if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) { break; } submatrix++; pivot.row++; } } public boolean isColumnZeroes(Coordinate a) { for (int i = 0; i < numRows; i++) { if (matrix.get(i).get(a.col).doubleValue() != 0.0) { return false; } } return true; } public boolean isRowZeroes(Coordinate a) { for (int i = 0; i < numCols; i++) { if (matrix.get(a.row).get(i).doubleValue() != 0.0) { return false; } } return true; } public Coordinate findPivot(Coordinate a) { int first_row = a.row; Coordinate pivot = new Coordinate(a.row, a.col); Coordinate current = new Coordinate(a.row, a.col); for (int i = a.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() == 1.0) { Interchange(current, a); } } current.row = a.row; for (int i = current.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() != 0) { pivot.row = i; break; } } return pivot; } public Fraction getCoordinate(Coordinate a) { return matrix.get(a.row).get(a.col); } public String toString() { return matrix.toString().replace("], ", "]\n"); } public static void main (String[] args) { double[][] matrix_1 = { {1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22} }; Matrix x = new Matrix(matrix_1); System.out.println("before\n" + x.toString() + "\n"); x.RREF(); System.out.println("after\n" + x.toString() + "\n"); double matrix_2 [][] = { {2, 0, -1, 0, 0}, {1, 0, 0, -1, 0}, {3, 0, 0, -2, -1}, {0, 1, 0, 0, -2}, {0, 1, -1, 0, 0} }; Matrix y = new Matrix(matrix_2); System.out.println("before\n" + y.toString() + "\n"); y.RREF(); System.out.println("after\n" + y.toString() + "\n"); double matrix_3 [][] = { {1, 2, 3, 4, 3, 1}, {2, 4, 6, 2, 6, 2}, {3, 6, 18, 9, 9, -6}, {4, 8, 12, 10, 12, 4}, {5, 10, 24, 11, 15, -4} }; Matrix z = new Matrix(matrix_3); System.out.println("before\n" + z.toString() + "\n"); z.RREF(); System.out.println("after\n" + z.toString() + "\n"); double matrix_4 [][] = { {0, 1}, {1, 2}, {0,5} }; Matrix a = new Matrix(matrix_4); System.out.println("before\n" + a.toString() + "\n"); a.RREF(); System.out.println("after\n" + a.toString() + "\n"); } }
Produce a functionally identical Python code for the snippet given in Racket.
#lang racket (require math) (define (reduced-echelon M) (matrix-row-echelon M #t #t)) (reduced-echelon (matrix [[1 2 -1 -4] [2 3 -1 -11] [-2 0 -3 22]]))
def ToReducedRowEchelonForm( M): if not M: return lead = 0 rowCount = len(M) columnCount = len(M[0]) for r in range(rowCount): if lead >= columnCount: return i = r while M[i][lead] == 0: i += 1 if i == rowCount: i = r lead += 1 if columnCount == lead: return M[i],M[r] = M[r],M[i] lv = M[r][lead] M[r] = [ mrx / float(lv) for mrx in M[r]] for i in range(rowCount): if i != r: lv = M[i][lead] M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])] lead += 1 mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22],] ToReducedRowEchelonForm( mtx ) for rw in mtx: print ', '.join( (str(rv) for rv in rw) )
Maintain the same structure and functionality when rewriting this code in VB.
#lang racket (require math) (define (reduced-echelon M) (matrix-row-echelon M #t #t)) (reduced-echelon (matrix [[1 2 -1 -4] [2 3 -1 -11] [-2 0 -3 22]]))
Private Function ToReducedRowEchelonForm(M As Variant) As Variant Dim lead As Integer: lead = 0 Dim rowCount As Integer: rowCount = UBound(M) Dim columnCount As Integer: columnCount = UBound(M(0)) Dim i As Integer For r = 0 To rowCount If lead >= columnCount Then Exit For End If i = r Do While M(i)(lead) = 0 i = i + 1 If i = rowCount Then i = r lead = lead + 1 If lead = columnCount Then Exit For End If End If Loop Dim tmp As Variant tmp = M(r) M(r) = M(i) M(i) = tmp If M(r)(lead) <> 0 Then div = M(r)(lead) For t = LBound(M(r)) To UBound(M(r)) M(r)(t) = M(r)(t) / div Next t End If For j = 0 To rowCount If j <> r Then subt = M(j)(lead) For t = LBound(M(j)) To UBound(M(j)) M(j)(t) = M(j)(t) - subt * M(r)(t) Next t End If Next j lead = lead + 1 Next r ToReducedRowEchelonForm = M End Function Public Sub main() r = ToReducedRowEchelonForm(Array( _ Array(1, 2, -1, -4), _ Array(2, 3, -1, -11), _ Array(-2, 0, -3, 22))) For i = LBound(r) To UBound(r) Debug.Print Join(r(i), vbTab) Next i End Sub
Rewrite this program in Go while keeping its functionality equivalent to the Racket version.
#lang racket (require math) (define (reduced-echelon M) (matrix-row-echelon M #t #t)) (reduced-echelon (matrix [[1 2 -1 -4] [2 3 -1 -11] [-2 0 -3 22]]))
package main import "fmt" type matrix [][]float64 func (m matrix) print() { for _, r := range m { fmt.Println(r) } fmt.Println("") } func main() { m := matrix{ { 1, 2, -1, -4}, { 2, 3, -1, -11}, {-2, 0, -3, 22}, } m.print() rref(m) m.print() } func rref(m matrix) { lead := 0 rowCount := len(m) columnCount := len(m[0]) for r := 0; r < rowCount; r++ { if lead >= columnCount { return } i := r for m[i][lead] == 0 { i++ if rowCount == i { i = r lead++ if columnCount == lead { return } } } m[i], m[r] = m[r], m[i] f := 1 / m[r][lead] for j, _ := range m[r] { m[r][j] *= f } for i = 0; i < rowCount; i++ { if i != r { f = m[i][lead] for j, e := range m[r] { m[i][j] -= e * f } } } lead++ } }
Ensure the translated C code behaves exactly like the original REXX snippet.
cols= 0; w= 0; @. =0 mat.=; mat.1= ' 1 2 -1 -4 ' mat.2= ' 2 3 -1 -11 ' mat.3= ' -2 0 -3 22 ' do r=1 until mat.r==''; _=mat.r do c=1 until _=''; parse var _ @.r.c _ w= max(w, length(@.r.c) + 1) end cols= max(cols, c) end rows= r-1 call showMat 'original matrix' != 1 do r=1 for rows while cols>! j= r do while @.j.!==0; j= j + 1 if j==rows then do; j= r; != ! + 1; if cols==! then leave r; end end do _=1 for cols while j\==r; parse value @.r._ @.j._ with @.j._ @._._ end ?= @.r.! do d=1 for cols while ?\=1; @.r.d= @.r.d / ? end do k=1 for rows; ?= @.k.! if k==r | ?=0 then iterate do s=1 for cols; @.k.s= @.k.s - ? * @.r.s end end != !+1 end call showMat 'matrix RREF' exit showMat: parse arg title; say; say center(title, 3 + (cols+1) * w, '─'); say do r=1 for rows; _= do c=1 for cols if @.r.c=='' then do; say "***error*** matrix element isn't defined:" say 'row' r", column" c'.'; exit 13 end _= _ right(@.r.c, w) end say _ end
#include <stdio.h> #define TALLOC(n,typ) malloc(n*sizeof(typ)) #define EL_Type int typedef struct sMtx { int dim_x, dim_y; EL_Type *m_stor; EL_Type **mtx; } *Matrix, sMatrix; typedef struct sRvec { int dim_x; EL_Type *m_stor; } *RowVec, sRowVec; Matrix NewMatrix( int x_dim, int y_dim ) { int n; Matrix m; m = TALLOC( 1, sMatrix); n = x_dim * y_dim; m->dim_x = x_dim; m->dim_y = y_dim; m->m_stor = TALLOC(n, EL_Type); m->mtx = TALLOC(m->dim_y, EL_Type *); for(n=0; n<y_dim; n++) { m->mtx[n] = m->m_stor+n*x_dim; } return m; } void MtxSetRow(Matrix m, int irow, EL_Type *v) { int ix; EL_Type *mr; mr = m->mtx[irow]; for(ix=0; ix<m->dim_x; ix++) mr[ix] = v[ix]; } Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v) { Matrix m; int iy; m = NewMatrix(x_dim, y_dim); for (iy=0; iy<y_dim; iy++) MtxSetRow(m, iy, v[iy]); return m; } void MtxDisplay( Matrix m ) { int iy, ix; const char *sc; for (iy=0; iy<m->dim_y; iy++) { printf(" "); sc = " "; for (ix=0; ix<m->dim_x; ix++) { printf("%s %3d", sc, m->mtx[iy][ix]); sc = ","; } printf("\n"); } printf("\n"); } void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr) { int ix; EL_Type *drow, *srow; drow = m->mtx[ixrdest]; srow = m->mtx[ixrsrc]; for (ix=0; ix<m->dim_x; ix++) drow[ix] += mplr * srow[ix]; } void MtxSwapRows( Matrix m, int rix1, int rix2) { EL_Type *r1, *r2, temp; int ix; if (rix1 == rix2) return; r1 = m->mtx[rix1]; r2 = m->mtx[rix2]; for (ix=0; ix<m->dim_x; ix++) temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp; } void MtxNormalizeRow( Matrix m, int rix, int lead) { int ix; EL_Type *drow; EL_Type lv; drow = m->mtx[rix]; lv = drow[lead]; for (ix=0; ix<m->dim_x; ix++) drow[ix] /= lv; } #define MtxGet( m, rix, cix ) m->mtx[rix][cix] void MtxToReducedREForm(Matrix m) { int lead; int rix, iix; EL_Type lv; int rowCount = m->dim_y; lead = 0; for (rix=0; rix<rowCount; rix++) { if (lead >= m->dim_x) return; iix = rix; while (0 == MtxGet(m, iix,lead)) { iix++; if (iix == rowCount) { iix = rix; lead++; if (lead == m->dim_x) return; } } MtxSwapRows(m, iix, rix ); MtxNormalizeRow(m, rix, lead ); for (iix=0; iix<rowCount; iix++) { if ( iix != rix ) { lv = MtxGet(m, iix, lead ); MtxMulAndAddRows(m,iix, rix, -lv) ; } } lead++; } } int main() { Matrix m1; static EL_Type r1[] = {1,2,-1,-4}; static EL_Type r2[] = {2,3,-1,-11}; static EL_Type r3[] = {-2,0,-3,22}; static EL_Type *im[] = { r1, r2, r3 }; m1 = InitMatrix( 4,3, im ); printf("Initial\n"); MtxDisplay(m1); MtxToReducedREForm(m1); printf("Reduced R-E form\n"); MtxDisplay(m1); return 0; }
Generate a C# translation of this REXX snippet without changing its computational steps.
cols= 0; w= 0; @. =0 mat.=; mat.1= ' 1 2 -1 -4 ' mat.2= ' 2 3 -1 -11 ' mat.3= ' -2 0 -3 22 ' do r=1 until mat.r==''; _=mat.r do c=1 until _=''; parse var _ @.r.c _ w= max(w, length(@.r.c) + 1) end cols= max(cols, c) end rows= r-1 call showMat 'original matrix' != 1 do r=1 for rows while cols>! j= r do while @.j.!==0; j= j + 1 if j==rows then do; j= r; != ! + 1; if cols==! then leave r; end end do _=1 for cols while j\==r; parse value @.r._ @.j._ with @.j._ @._._ end ?= @.r.! do d=1 for cols while ?\=1; @.r.d= @.r.d / ? end do k=1 for rows; ?= @.k.! if k==r | ?=0 then iterate do s=1 for cols; @.k.s= @.k.s - ? * @.r.s end end != !+1 end call showMat 'matrix RREF' exit showMat: parse arg title; say; say center(title, 3 + (cols+1) * w, '─'); say do r=1 for rows; _= do c=1 for cols if @.r.c=='' then do; say "***error*** matrix element isn't defined:" say 'row' r", column" c'.'; exit 13 end _= _ right(@.r.c, w) end say _ end
using System; namespace rref { class Program { static void Main(string[] args) { int[,] matrix = new int[3, 4]{ { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; matrix = rref(matrix); } private static int[,] rref(int[,] matrix) { int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1); for (int r = 0; r < rowCount; r++) { if (columnCount <= lead) break; int i = r; while (matrix[i, lead] == 0) { i++; if (i == rowCount) { i = r; lead++; if (columnCount == lead) { lead--; break; } } } for (int j = 0; j < columnCount; j++) { int temp = matrix[r, j]; matrix[r, j] = matrix[i, j]; matrix[i, j] = temp; } int div = matrix[r, lead]; if(div != 0) for (int j = 0; j < columnCount; j++) matrix[r, j] /= div; for (int j = 0; j < rowCount; j++) { if (j != r) { int sub = matrix[j, lead]; for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]); } } lead++; } return matrix; } } }
Transform the following REXX implementation into C++, maintaining the same output and logic.
cols= 0; w= 0; @. =0 mat.=; mat.1= ' 1 2 -1 -4 ' mat.2= ' 2 3 -1 -11 ' mat.3= ' -2 0 -3 22 ' do r=1 until mat.r==''; _=mat.r do c=1 until _=''; parse var _ @.r.c _ w= max(w, length(@.r.c) + 1) end cols= max(cols, c) end rows= r-1 call showMat 'original matrix' != 1 do r=1 for rows while cols>! j= r do while @.j.!==0; j= j + 1 if j==rows then do; j= r; != ! + 1; if cols==! then leave r; end end do _=1 for cols while j\==r; parse value @.r._ @.j._ with @.j._ @._._ end ?= @.r.! do d=1 for cols while ?\=1; @.r.d= @.r.d / ? end do k=1 for rows; ?= @.k.! if k==r | ?=0 then iterate do s=1 for cols; @.k.s= @.k.s - ? * @.r.s end end != !+1 end call showMat 'matrix RREF' exit showMat: parse arg title; say; say center(title, 3 + (cols+1) * w, '─'); say do r=1 for rows; _= do c=1 for cols if @.r.c=='' then do; say "***error*** matrix element isn't defined:" say 'row' r", column" c'.'; exit 13 end _= _ right(@.r.c, w) end say _ end
#include <algorithm> #include <cstddef> #include <cassert> template<typename MatrixType> struct matrix_traits { typedef typename MatrixType::index_type index_type; typedef typename MatrixType::value_type value_type; static index_type min_row(MatrixType const& A) { return A.min_row(); } static index_type max_row(MatrixType const& A) { return A.max_row(); } static index_type min_column(MatrixType const& A) { return A.min_column(); } static index_type max_column(MatrixType const& A) { return A.max_column(); } static value_type& element(MatrixType& A, index_type i, index_type k) { return A(i,k); } static value_type element(MatrixType const& A, index_type i, index_type k) { return A(i,k); } }; template<typename T, std::size_t rows, std::size_t columns> struct matrix_traits<T[rows][columns]> { typedef std::size_t index_type; typedef T value_type; static index_type min_row(T const (&)[rows][columns]) { return 0; } static index_type max_row(T const (&)[rows][columns]) { return rows-1; } static index_type min_column(T const (&)[rows][columns]) { return 0; } static index_type max_column(T const (&)[rows][columns]) { return columns-1; } static value_type& element(T (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } static value_type element(T const (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } }; template<typename MatrixType> void swap_rows(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) std::swap(mt.element(A, i, col), mt.element(A, k, col)); } template<typename MatrixType> void divide_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(v != 0); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) /= v; } template<typename MatrixType> void add_multiple_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) += v * mt.element(A, k, col); } template<typename MatrixType> void to_reduced_row_echelon_form(MatrixType& A) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; index_type lead = mt.min_row(A); for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row) { if (lead > mt.max_column(A)) return; index_type i = row; while (mt.element(A, i, lead) == 0) { ++i; if (i > mt.max_row(A)) { i = row; ++lead; if (lead > mt.max_column(A)) return; } } swap_rows(A, i, row); divide_row(A, row, mt.element(A, row, lead)); for (i = mt.min_row(A); i <= mt.max_row(A); ++i) { if (i != row) add_multiple_row(A, i, row, -mt.element(A, i, lead)); } } } #include <iostream> int main() { double M[3][4] = { { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; to_reduced_row_echelon_form(M); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) std::cout << M[i][j] << '\t'; std::cout << "\n"; } return EXIT_SUCCESS; }
Write the same code in Java as shown below in REXX.
cols= 0; w= 0; @. =0 mat.=; mat.1= ' 1 2 -1 -4 ' mat.2= ' 2 3 -1 -11 ' mat.3= ' -2 0 -3 22 ' do r=1 until mat.r==''; _=mat.r do c=1 until _=''; parse var _ @.r.c _ w= max(w, length(@.r.c) + 1) end cols= max(cols, c) end rows= r-1 call showMat 'original matrix' != 1 do r=1 for rows while cols>! j= r do while @.j.!==0; j= j + 1 if j==rows then do; j= r; != ! + 1; if cols==! then leave r; end end do _=1 for cols while j\==r; parse value @.r._ @.j._ with @.j._ @._._ end ?= @.r.! do d=1 for cols while ?\=1; @.r.d= @.r.d / ? end do k=1 for rows; ?= @.k.! if k==r | ?=0 then iterate do s=1 for cols; @.k.s= @.k.s - ? * @.r.s end end != !+1 end call showMat 'matrix RREF' exit showMat: parse arg title; say; say center(title, 3 + (cols+1) * w, '─'); say do r=1 for rows; _= do c=1 for cols if @.r.c=='' then do; say "***error*** matrix element isn't defined:" say 'row' r", column" c'.'; exit 13 end _= _ right(@.r.c, w) end say _ end
import java.util.*; import java.lang.Math; import org.apache.commons.math.fraction.Fraction; import org.apache.commons.math.fraction.FractionConversionException; class Matrix { LinkedList<LinkedList<Fraction>> matrix; int numRows; int numCols; static class Coordinate { int row; int col; Coordinate(int r, int c) { row = r; col = c; } public String toString() { return "(" + row + ", " + col + ")"; } } Matrix(double [][] m) { numRows = m.length; numCols = m[0].length; matrix = new LinkedList<LinkedList<Fraction>>(); for (int i = 0; i < numRows; i++) { matrix.add(new LinkedList<Fraction>()); for (int j = 0; j < numCols; j++) { try { matrix.get(i).add(new Fraction(m[i][j])); } catch (FractionConversionException e) { System.err.println("Fraction could not be converted from double by apache commons . . ."); } } } } public void Interchange(Coordinate a, Coordinate b) { LinkedList<Fraction> temp = matrix.get(a.row); matrix.set(a.row, matrix.get(b.row)); matrix.set(b.row, temp); int t = a.row; a.row = b.row; b.row = t; } public void Scale(Coordinate x, Fraction d) { LinkedList<Fraction> row = matrix.get(x.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).multiply(d)); } } public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) { LinkedList<Fraction> row = matrix.get(to.row); LinkedList<Fraction> rowMultiplied = matrix.get(from.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar)))); } } public void RREF() { Coordinate pivot = new Coordinate(0,0); int submatrix = 0; for (int x = 0; x < numCols; x++) { pivot = new Coordinate(pivot.row, x); for (int i = x; i < numCols; i++) { if (isColumnZeroes(pivot) == false) { break; } else { pivot.col = i; } } pivot = findPivot(pivot); if (getCoordinate(pivot).doubleValue() == 0.0) { pivot.row++; continue; } if (pivot.row != submatrix) { Interchange(new Coordinate(submatrix, pivot.col), pivot); } if (getCoordinate(pivot).doubleValue() != 1) { Fraction scalar = getCoordinate(pivot).reciprocal(); Scale(pivot, scalar); } for (int i = pivot.row; i < numRows; i++) { if (i == pivot.row) { continue; } Coordinate belowPivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(belowPivot, pivot, complement); } for (int i = pivot.row; i >= 0; i--) { if (i == pivot.row) { if (getCoordinate(pivot).doubleValue() != 1.0) { Scale(pivot, getCoordinate(pivot).reciprocal()); } continue; } if (i == pivot.row) { continue; } Coordinate abovePivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(abovePivot, pivot, complement); } if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) { break; } submatrix++; pivot.row++; } } public boolean isColumnZeroes(Coordinate a) { for (int i = 0; i < numRows; i++) { if (matrix.get(i).get(a.col).doubleValue() != 0.0) { return false; } } return true; } public boolean isRowZeroes(Coordinate a) { for (int i = 0; i < numCols; i++) { if (matrix.get(a.row).get(i).doubleValue() != 0.0) { return false; } } return true; } public Coordinate findPivot(Coordinate a) { int first_row = a.row; Coordinate pivot = new Coordinate(a.row, a.col); Coordinate current = new Coordinate(a.row, a.col); for (int i = a.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() == 1.0) { Interchange(current, a); } } current.row = a.row; for (int i = current.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() != 0) { pivot.row = i; break; } } return pivot; } public Fraction getCoordinate(Coordinate a) { return matrix.get(a.row).get(a.col); } public String toString() { return matrix.toString().replace("], ", "]\n"); } public static void main (String[] args) { double[][] matrix_1 = { {1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22} }; Matrix x = new Matrix(matrix_1); System.out.println("before\n" + x.toString() + "\n"); x.RREF(); System.out.println("after\n" + x.toString() + "\n"); double matrix_2 [][] = { {2, 0, -1, 0, 0}, {1, 0, 0, -1, 0}, {3, 0, 0, -2, -1}, {0, 1, 0, 0, -2}, {0, 1, -1, 0, 0} }; Matrix y = new Matrix(matrix_2); System.out.println("before\n" + y.toString() + "\n"); y.RREF(); System.out.println("after\n" + y.toString() + "\n"); double matrix_3 [][] = { {1, 2, 3, 4, 3, 1}, {2, 4, 6, 2, 6, 2}, {3, 6, 18, 9, 9, -6}, {4, 8, 12, 10, 12, 4}, {5, 10, 24, 11, 15, -4} }; Matrix z = new Matrix(matrix_3); System.out.println("before\n" + z.toString() + "\n"); z.RREF(); System.out.println("after\n" + z.toString() + "\n"); double matrix_4 [][] = { {0, 1}, {1, 2}, {0,5} }; Matrix a = new Matrix(matrix_4); System.out.println("before\n" + a.toString() + "\n"); a.RREF(); System.out.println("after\n" + a.toString() + "\n"); } }
Rewrite this program in Python while keeping its functionality equivalent to the REXX version.
cols= 0; w= 0; @. =0 mat.=; mat.1= ' 1 2 -1 -4 ' mat.2= ' 2 3 -1 -11 ' mat.3= ' -2 0 -3 22 ' do r=1 until mat.r==''; _=mat.r do c=1 until _=''; parse var _ @.r.c _ w= max(w, length(@.r.c) + 1) end cols= max(cols, c) end rows= r-1 call showMat 'original matrix' != 1 do r=1 for rows while cols>! j= r do while @.j.!==0; j= j + 1 if j==rows then do; j= r; != ! + 1; if cols==! then leave r; end end do _=1 for cols while j\==r; parse value @.r._ @.j._ with @.j._ @._._ end ?= @.r.! do d=1 for cols while ?\=1; @.r.d= @.r.d / ? end do k=1 for rows; ?= @.k.! if k==r | ?=0 then iterate do s=1 for cols; @.k.s= @.k.s - ? * @.r.s end end != !+1 end call showMat 'matrix RREF' exit showMat: parse arg title; say; say center(title, 3 + (cols+1) * w, '─'); say do r=1 for rows; _= do c=1 for cols if @.r.c=='' then do; say "***error*** matrix element isn't defined:" say 'row' r", column" c'.'; exit 13 end _= _ right(@.r.c, w) end say _ end
def ToReducedRowEchelonForm( M): if not M: return lead = 0 rowCount = len(M) columnCount = len(M[0]) for r in range(rowCount): if lead >= columnCount: return i = r while M[i][lead] == 0: i += 1 if i == rowCount: i = r lead += 1 if columnCount == lead: return M[i],M[r] = M[r],M[i] lv = M[r][lead] M[r] = [ mrx / float(lv) for mrx in M[r]] for i in range(rowCount): if i != r: lv = M[i][lead] M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])] lead += 1 mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22],] ToReducedRowEchelonForm( mtx ) for rw in mtx: print ', '.join( (str(rv) for rv in rw) )
Port the provided REXX code into VB while preserving the original functionality.
cols= 0; w= 0; @. =0 mat.=; mat.1= ' 1 2 -1 -4 ' mat.2= ' 2 3 -1 -11 ' mat.3= ' -2 0 -3 22 ' do r=1 until mat.r==''; _=mat.r do c=1 until _=''; parse var _ @.r.c _ w= max(w, length(@.r.c) + 1) end cols= max(cols, c) end rows= r-1 call showMat 'original matrix' != 1 do r=1 for rows while cols>! j= r do while @.j.!==0; j= j + 1 if j==rows then do; j= r; != ! + 1; if cols==! then leave r; end end do _=1 for cols while j\==r; parse value @.r._ @.j._ with @.j._ @._._ end ?= @.r.! do d=1 for cols while ?\=1; @.r.d= @.r.d / ? end do k=1 for rows; ?= @.k.! if k==r | ?=0 then iterate do s=1 for cols; @.k.s= @.k.s - ? * @.r.s end end != !+1 end call showMat 'matrix RREF' exit showMat: parse arg title; say; say center(title, 3 + (cols+1) * w, '─'); say do r=1 for rows; _= do c=1 for cols if @.r.c=='' then do; say "***error*** matrix element isn't defined:" say 'row' r", column" c'.'; exit 13 end _= _ right(@.r.c, w) end say _ end
Private Function ToReducedRowEchelonForm(M As Variant) As Variant Dim lead As Integer: lead = 0 Dim rowCount As Integer: rowCount = UBound(M) Dim columnCount As Integer: columnCount = UBound(M(0)) Dim i As Integer For r = 0 To rowCount If lead >= columnCount Then Exit For End If i = r Do While M(i)(lead) = 0 i = i + 1 If i = rowCount Then i = r lead = lead + 1 If lead = columnCount Then Exit For End If End If Loop Dim tmp As Variant tmp = M(r) M(r) = M(i) M(i) = tmp If M(r)(lead) <> 0 Then div = M(r)(lead) For t = LBound(M(r)) To UBound(M(r)) M(r)(t) = M(r)(t) / div Next t End If For j = 0 To rowCount If j <> r Then subt = M(j)(lead) For t = LBound(M(j)) To UBound(M(j)) M(j)(t) = M(j)(t) - subt * M(r)(t) Next t End If Next j lead = lead + 1 Next r ToReducedRowEchelonForm = M End Function Public Sub main() r = ToReducedRowEchelonForm(Array( _ Array(1, 2, -1, -4), _ Array(2, 3, -1, -11), _ Array(-2, 0, -3, 22))) For i = LBound(r) To UBound(r) Debug.Print Join(r(i), vbTab) Next i End Sub
Produce a functionally identical Go code for the snippet given in REXX.
cols= 0; w= 0; @. =0 mat.=; mat.1= ' 1 2 -1 -4 ' mat.2= ' 2 3 -1 -11 ' mat.3= ' -2 0 -3 22 ' do r=1 until mat.r==''; _=mat.r do c=1 until _=''; parse var _ @.r.c _ w= max(w, length(@.r.c) + 1) end cols= max(cols, c) end rows= r-1 call showMat 'original matrix' != 1 do r=1 for rows while cols>! j= r do while @.j.!==0; j= j + 1 if j==rows then do; j= r; != ! + 1; if cols==! then leave r; end end do _=1 for cols while j\==r; parse value @.r._ @.j._ with @.j._ @._._ end ?= @.r.! do d=1 for cols while ?\=1; @.r.d= @.r.d / ? end do k=1 for rows; ?= @.k.! if k==r | ?=0 then iterate do s=1 for cols; @.k.s= @.k.s - ? * @.r.s end end != !+1 end call showMat 'matrix RREF' exit showMat: parse arg title; say; say center(title, 3 + (cols+1) * w, '─'); say do r=1 for rows; _= do c=1 for cols if @.r.c=='' then do; say "***error*** matrix element isn't defined:" say 'row' r", column" c'.'; exit 13 end _= _ right(@.r.c, w) end say _ end
package main import "fmt" type matrix [][]float64 func (m matrix) print() { for _, r := range m { fmt.Println(r) } fmt.Println("") } func main() { m := matrix{ { 1, 2, -1, -4}, { 2, 3, -1, -11}, {-2, 0, -3, 22}, } m.print() rref(m) m.print() } func rref(m matrix) { lead := 0 rowCount := len(m) columnCount := len(m[0]) for r := 0; r < rowCount; r++ { if lead >= columnCount { return } i := r for m[i][lead] == 0 { i++ if rowCount == i { i = r lead++ if columnCount == lead { return } } } m[i], m[r] = m[r], m[i] f := 1 / m[r][lead] for j, _ := range m[r] { m[r][j] *= f } for i = 0; i < rowCount; i++ { if i != r { f = m[i][lead] for j, e := range m[r] { m[i][j] -= e * f } } } lead++ } }
Change the following Ruby code into C without altering its purpose.
def reduced_row_echelon_form(ary) lead = 0 rows = ary.size cols = ary[0].size rary = convert_to(ary, :to_r) catch :done do rows.times do |r| throw :done if cols <= lead i = r while rary[i][lead] == 0 i += 1 if rows == i i = r lead += 1 throw :done if cols == lead end end rary[i], rary[r] = rary[r], rary[i] v = rary[r][lead] rary[r].collect! {|x| x / v} rows.times do |i| next if i == r v = rary[i][lead] rary[i].each_index {|j| rary[i][j] -= v * rary[r][j]} end lead += 1 end end rary end def convert_to(ary, type) ary.each_with_object([]) do |row, new| new << row.collect {|elem| elem.send(type)} end end class Rational alias _to_s to_s def to_s denominator==1 ? numerator.to_s : _to_s end end def print_matrix(m) max = m[0].collect {-1} m.each {|row| row.each_index {|i| max[i] = [max[i], row[i].to_s.length].max}} m.each {|row| row.each_index {|i| print "% end mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1,-11], [-2, 0, -3, 22] ] print_matrix reduced_row_echelon_form(mtx) puts mtx = [ [ 1, 2, 3, 7], [-4, 7,-2, 7], [ 3, 3, 0, 7] ] reduced = reduced_row_echelon_form(mtx) print_matrix reduced print_matrix convert_to(reduced, :to_f)
#include <stdio.h> #define TALLOC(n,typ) malloc(n*sizeof(typ)) #define EL_Type int typedef struct sMtx { int dim_x, dim_y; EL_Type *m_stor; EL_Type **mtx; } *Matrix, sMatrix; typedef struct sRvec { int dim_x; EL_Type *m_stor; } *RowVec, sRowVec; Matrix NewMatrix( int x_dim, int y_dim ) { int n; Matrix m; m = TALLOC( 1, sMatrix); n = x_dim * y_dim; m->dim_x = x_dim; m->dim_y = y_dim; m->m_stor = TALLOC(n, EL_Type); m->mtx = TALLOC(m->dim_y, EL_Type *); for(n=0; n<y_dim; n++) { m->mtx[n] = m->m_stor+n*x_dim; } return m; } void MtxSetRow(Matrix m, int irow, EL_Type *v) { int ix; EL_Type *mr; mr = m->mtx[irow]; for(ix=0; ix<m->dim_x; ix++) mr[ix] = v[ix]; } Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v) { Matrix m; int iy; m = NewMatrix(x_dim, y_dim); for (iy=0; iy<y_dim; iy++) MtxSetRow(m, iy, v[iy]); return m; } void MtxDisplay( Matrix m ) { int iy, ix; const char *sc; for (iy=0; iy<m->dim_y; iy++) { printf(" "); sc = " "; for (ix=0; ix<m->dim_x; ix++) { printf("%s %3d", sc, m->mtx[iy][ix]); sc = ","; } printf("\n"); } printf("\n"); } void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr) { int ix; EL_Type *drow, *srow; drow = m->mtx[ixrdest]; srow = m->mtx[ixrsrc]; for (ix=0; ix<m->dim_x; ix++) drow[ix] += mplr * srow[ix]; } void MtxSwapRows( Matrix m, int rix1, int rix2) { EL_Type *r1, *r2, temp; int ix; if (rix1 == rix2) return; r1 = m->mtx[rix1]; r2 = m->mtx[rix2]; for (ix=0; ix<m->dim_x; ix++) temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp; } void MtxNormalizeRow( Matrix m, int rix, int lead) { int ix; EL_Type *drow; EL_Type lv; drow = m->mtx[rix]; lv = drow[lead]; for (ix=0; ix<m->dim_x; ix++) drow[ix] /= lv; } #define MtxGet( m, rix, cix ) m->mtx[rix][cix] void MtxToReducedREForm(Matrix m) { int lead; int rix, iix; EL_Type lv; int rowCount = m->dim_y; lead = 0; for (rix=0; rix<rowCount; rix++) { if (lead >= m->dim_x) return; iix = rix; while (0 == MtxGet(m, iix,lead)) { iix++; if (iix == rowCount) { iix = rix; lead++; if (lead == m->dim_x) return; } } MtxSwapRows(m, iix, rix ); MtxNormalizeRow(m, rix, lead ); for (iix=0; iix<rowCount; iix++) { if ( iix != rix ) { lv = MtxGet(m, iix, lead ); MtxMulAndAddRows(m,iix, rix, -lv) ; } } lead++; } } int main() { Matrix m1; static EL_Type r1[] = {1,2,-1,-4}; static EL_Type r2[] = {2,3,-1,-11}; static EL_Type r3[] = {-2,0,-3,22}; static EL_Type *im[] = { r1, r2, r3 }; m1 = InitMatrix( 4,3, im ); printf("Initial\n"); MtxDisplay(m1); MtxToReducedREForm(m1); printf("Reduced R-E form\n"); MtxDisplay(m1); return 0; }
Generate an equivalent C# version of this Ruby code.
def reduced_row_echelon_form(ary) lead = 0 rows = ary.size cols = ary[0].size rary = convert_to(ary, :to_r) catch :done do rows.times do |r| throw :done if cols <= lead i = r while rary[i][lead] == 0 i += 1 if rows == i i = r lead += 1 throw :done if cols == lead end end rary[i], rary[r] = rary[r], rary[i] v = rary[r][lead] rary[r].collect! {|x| x / v} rows.times do |i| next if i == r v = rary[i][lead] rary[i].each_index {|j| rary[i][j] -= v * rary[r][j]} end lead += 1 end end rary end def convert_to(ary, type) ary.each_with_object([]) do |row, new| new << row.collect {|elem| elem.send(type)} end end class Rational alias _to_s to_s def to_s denominator==1 ? numerator.to_s : _to_s end end def print_matrix(m) max = m[0].collect {-1} m.each {|row| row.each_index {|i| max[i] = [max[i], row[i].to_s.length].max}} m.each {|row| row.each_index {|i| print "% end mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1,-11], [-2, 0, -3, 22] ] print_matrix reduced_row_echelon_form(mtx) puts mtx = [ [ 1, 2, 3, 7], [-4, 7,-2, 7], [ 3, 3, 0, 7] ] reduced = reduced_row_echelon_form(mtx) print_matrix reduced print_matrix convert_to(reduced, :to_f)
using System; namespace rref { class Program { static void Main(string[] args) { int[,] matrix = new int[3, 4]{ { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; matrix = rref(matrix); } private static int[,] rref(int[,] matrix) { int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1); for (int r = 0; r < rowCount; r++) { if (columnCount <= lead) break; int i = r; while (matrix[i, lead] == 0) { i++; if (i == rowCount) { i = r; lead++; if (columnCount == lead) { lead--; break; } } } for (int j = 0; j < columnCount; j++) { int temp = matrix[r, j]; matrix[r, j] = matrix[i, j]; matrix[i, j] = temp; } int div = matrix[r, lead]; if(div != 0) for (int j = 0; j < columnCount; j++) matrix[r, j] /= div; for (int j = 0; j < rowCount; j++) { if (j != r) { int sub = matrix[j, lead]; for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]); } } lead++; } return matrix; } } }
Write a version of this Ruby function in C++ with identical behavior.
def reduced_row_echelon_form(ary) lead = 0 rows = ary.size cols = ary[0].size rary = convert_to(ary, :to_r) catch :done do rows.times do |r| throw :done if cols <= lead i = r while rary[i][lead] == 0 i += 1 if rows == i i = r lead += 1 throw :done if cols == lead end end rary[i], rary[r] = rary[r], rary[i] v = rary[r][lead] rary[r].collect! {|x| x / v} rows.times do |i| next if i == r v = rary[i][lead] rary[i].each_index {|j| rary[i][j] -= v * rary[r][j]} end lead += 1 end end rary end def convert_to(ary, type) ary.each_with_object([]) do |row, new| new << row.collect {|elem| elem.send(type)} end end class Rational alias _to_s to_s def to_s denominator==1 ? numerator.to_s : _to_s end end def print_matrix(m) max = m[0].collect {-1} m.each {|row| row.each_index {|i| max[i] = [max[i], row[i].to_s.length].max}} m.each {|row| row.each_index {|i| print "% end mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1,-11], [-2, 0, -3, 22] ] print_matrix reduced_row_echelon_form(mtx) puts mtx = [ [ 1, 2, 3, 7], [-4, 7,-2, 7], [ 3, 3, 0, 7] ] reduced = reduced_row_echelon_form(mtx) print_matrix reduced print_matrix convert_to(reduced, :to_f)
#include <algorithm> #include <cstddef> #include <cassert> template<typename MatrixType> struct matrix_traits { typedef typename MatrixType::index_type index_type; typedef typename MatrixType::value_type value_type; static index_type min_row(MatrixType const& A) { return A.min_row(); } static index_type max_row(MatrixType const& A) { return A.max_row(); } static index_type min_column(MatrixType const& A) { return A.min_column(); } static index_type max_column(MatrixType const& A) { return A.max_column(); } static value_type& element(MatrixType& A, index_type i, index_type k) { return A(i,k); } static value_type element(MatrixType const& A, index_type i, index_type k) { return A(i,k); } }; template<typename T, std::size_t rows, std::size_t columns> struct matrix_traits<T[rows][columns]> { typedef std::size_t index_type; typedef T value_type; static index_type min_row(T const (&)[rows][columns]) { return 0; } static index_type max_row(T const (&)[rows][columns]) { return rows-1; } static index_type min_column(T const (&)[rows][columns]) { return 0; } static index_type max_column(T const (&)[rows][columns]) { return columns-1; } static value_type& element(T (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } static value_type element(T const (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } }; template<typename MatrixType> void swap_rows(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) std::swap(mt.element(A, i, col), mt.element(A, k, col)); } template<typename MatrixType> void divide_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(v != 0); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) /= v; } template<typename MatrixType> void add_multiple_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) += v * mt.element(A, k, col); } template<typename MatrixType> void to_reduced_row_echelon_form(MatrixType& A) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; index_type lead = mt.min_row(A); for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row) { if (lead > mt.max_column(A)) return; index_type i = row; while (mt.element(A, i, lead) == 0) { ++i; if (i > mt.max_row(A)) { i = row; ++lead; if (lead > mt.max_column(A)) return; } } swap_rows(A, i, row); divide_row(A, row, mt.element(A, row, lead)); for (i = mt.min_row(A); i <= mt.max_row(A); ++i) { if (i != row) add_multiple_row(A, i, row, -mt.element(A, i, lead)); } } } #include <iostream> int main() { double M[3][4] = { { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; to_reduced_row_echelon_form(M); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) std::cout << M[i][j] << '\t'; std::cout << "\n"; } return EXIT_SUCCESS; }
Convert this Ruby snippet to Java and keep its semantics consistent.
def reduced_row_echelon_form(ary) lead = 0 rows = ary.size cols = ary[0].size rary = convert_to(ary, :to_r) catch :done do rows.times do |r| throw :done if cols <= lead i = r while rary[i][lead] == 0 i += 1 if rows == i i = r lead += 1 throw :done if cols == lead end end rary[i], rary[r] = rary[r], rary[i] v = rary[r][lead] rary[r].collect! {|x| x / v} rows.times do |i| next if i == r v = rary[i][lead] rary[i].each_index {|j| rary[i][j] -= v * rary[r][j]} end lead += 1 end end rary end def convert_to(ary, type) ary.each_with_object([]) do |row, new| new << row.collect {|elem| elem.send(type)} end end class Rational alias _to_s to_s def to_s denominator==1 ? numerator.to_s : _to_s end end def print_matrix(m) max = m[0].collect {-1} m.each {|row| row.each_index {|i| max[i] = [max[i], row[i].to_s.length].max}} m.each {|row| row.each_index {|i| print "% end mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1,-11], [-2, 0, -3, 22] ] print_matrix reduced_row_echelon_form(mtx) puts mtx = [ [ 1, 2, 3, 7], [-4, 7,-2, 7], [ 3, 3, 0, 7] ] reduced = reduced_row_echelon_form(mtx) print_matrix reduced print_matrix convert_to(reduced, :to_f)
import java.util.*; import java.lang.Math; import org.apache.commons.math.fraction.Fraction; import org.apache.commons.math.fraction.FractionConversionException; class Matrix { LinkedList<LinkedList<Fraction>> matrix; int numRows; int numCols; static class Coordinate { int row; int col; Coordinate(int r, int c) { row = r; col = c; } public String toString() { return "(" + row + ", " + col + ")"; } } Matrix(double [][] m) { numRows = m.length; numCols = m[0].length; matrix = new LinkedList<LinkedList<Fraction>>(); for (int i = 0; i < numRows; i++) { matrix.add(new LinkedList<Fraction>()); for (int j = 0; j < numCols; j++) { try { matrix.get(i).add(new Fraction(m[i][j])); } catch (FractionConversionException e) { System.err.println("Fraction could not be converted from double by apache commons . . ."); } } } } public void Interchange(Coordinate a, Coordinate b) { LinkedList<Fraction> temp = matrix.get(a.row); matrix.set(a.row, matrix.get(b.row)); matrix.set(b.row, temp); int t = a.row; a.row = b.row; b.row = t; } public void Scale(Coordinate x, Fraction d) { LinkedList<Fraction> row = matrix.get(x.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).multiply(d)); } } public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) { LinkedList<Fraction> row = matrix.get(to.row); LinkedList<Fraction> rowMultiplied = matrix.get(from.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar)))); } } public void RREF() { Coordinate pivot = new Coordinate(0,0); int submatrix = 0; for (int x = 0; x < numCols; x++) { pivot = new Coordinate(pivot.row, x); for (int i = x; i < numCols; i++) { if (isColumnZeroes(pivot) == false) { break; } else { pivot.col = i; } } pivot = findPivot(pivot); if (getCoordinate(pivot).doubleValue() == 0.0) { pivot.row++; continue; } if (pivot.row != submatrix) { Interchange(new Coordinate(submatrix, pivot.col), pivot); } if (getCoordinate(pivot).doubleValue() != 1) { Fraction scalar = getCoordinate(pivot).reciprocal(); Scale(pivot, scalar); } for (int i = pivot.row; i < numRows; i++) { if (i == pivot.row) { continue; } Coordinate belowPivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(belowPivot, pivot, complement); } for (int i = pivot.row; i >= 0; i--) { if (i == pivot.row) { if (getCoordinate(pivot).doubleValue() != 1.0) { Scale(pivot, getCoordinate(pivot).reciprocal()); } continue; } if (i == pivot.row) { continue; } Coordinate abovePivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(abovePivot, pivot, complement); } if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) { break; } submatrix++; pivot.row++; } } public boolean isColumnZeroes(Coordinate a) { for (int i = 0; i < numRows; i++) { if (matrix.get(i).get(a.col).doubleValue() != 0.0) { return false; } } return true; } public boolean isRowZeroes(Coordinate a) { for (int i = 0; i < numCols; i++) { if (matrix.get(a.row).get(i).doubleValue() != 0.0) { return false; } } return true; } public Coordinate findPivot(Coordinate a) { int first_row = a.row; Coordinate pivot = new Coordinate(a.row, a.col); Coordinate current = new Coordinate(a.row, a.col); for (int i = a.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() == 1.0) { Interchange(current, a); } } current.row = a.row; for (int i = current.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() != 0) { pivot.row = i; break; } } return pivot; } public Fraction getCoordinate(Coordinate a) { return matrix.get(a.row).get(a.col); } public String toString() { return matrix.toString().replace("], ", "]\n"); } public static void main (String[] args) { double[][] matrix_1 = { {1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22} }; Matrix x = new Matrix(matrix_1); System.out.println("before\n" + x.toString() + "\n"); x.RREF(); System.out.println("after\n" + x.toString() + "\n"); double matrix_2 [][] = { {2, 0, -1, 0, 0}, {1, 0, 0, -1, 0}, {3, 0, 0, -2, -1}, {0, 1, 0, 0, -2}, {0, 1, -1, 0, 0} }; Matrix y = new Matrix(matrix_2); System.out.println("before\n" + y.toString() + "\n"); y.RREF(); System.out.println("after\n" + y.toString() + "\n"); double matrix_3 [][] = { {1, 2, 3, 4, 3, 1}, {2, 4, 6, 2, 6, 2}, {3, 6, 18, 9, 9, -6}, {4, 8, 12, 10, 12, 4}, {5, 10, 24, 11, 15, -4} }; Matrix z = new Matrix(matrix_3); System.out.println("before\n" + z.toString() + "\n"); z.RREF(); System.out.println("after\n" + z.toString() + "\n"); double matrix_4 [][] = { {0, 1}, {1, 2}, {0,5} }; Matrix a = new Matrix(matrix_4); System.out.println("before\n" + a.toString() + "\n"); a.RREF(); System.out.println("after\n" + a.toString() + "\n"); } }
Rewrite this program in Python while keeping its functionality equivalent to the Ruby version.
def reduced_row_echelon_form(ary) lead = 0 rows = ary.size cols = ary[0].size rary = convert_to(ary, :to_r) catch :done do rows.times do |r| throw :done if cols <= lead i = r while rary[i][lead] == 0 i += 1 if rows == i i = r lead += 1 throw :done if cols == lead end end rary[i], rary[r] = rary[r], rary[i] v = rary[r][lead] rary[r].collect! {|x| x / v} rows.times do |i| next if i == r v = rary[i][lead] rary[i].each_index {|j| rary[i][j] -= v * rary[r][j]} end lead += 1 end end rary end def convert_to(ary, type) ary.each_with_object([]) do |row, new| new << row.collect {|elem| elem.send(type)} end end class Rational alias _to_s to_s def to_s denominator==1 ? numerator.to_s : _to_s end end def print_matrix(m) max = m[0].collect {-1} m.each {|row| row.each_index {|i| max[i] = [max[i], row[i].to_s.length].max}} m.each {|row| row.each_index {|i| print "% end mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1,-11], [-2, 0, -3, 22] ] print_matrix reduced_row_echelon_form(mtx) puts mtx = [ [ 1, 2, 3, 7], [-4, 7,-2, 7], [ 3, 3, 0, 7] ] reduced = reduced_row_echelon_form(mtx) print_matrix reduced print_matrix convert_to(reduced, :to_f)
def ToReducedRowEchelonForm( M): if not M: return lead = 0 rowCount = len(M) columnCount = len(M[0]) for r in range(rowCount): if lead >= columnCount: return i = r while M[i][lead] == 0: i += 1 if i == rowCount: i = r lead += 1 if columnCount == lead: return M[i],M[r] = M[r],M[i] lv = M[r][lead] M[r] = [ mrx / float(lv) for mrx in M[r]] for i in range(rowCount): if i != r: lv = M[i][lead] M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])] lead += 1 mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22],] ToReducedRowEchelonForm( mtx ) for rw in mtx: print ', '.join( (str(rv) for rv in rw) )
Change the following Ruby code into VB without altering its purpose.
def reduced_row_echelon_form(ary) lead = 0 rows = ary.size cols = ary[0].size rary = convert_to(ary, :to_r) catch :done do rows.times do |r| throw :done if cols <= lead i = r while rary[i][lead] == 0 i += 1 if rows == i i = r lead += 1 throw :done if cols == lead end end rary[i], rary[r] = rary[r], rary[i] v = rary[r][lead] rary[r].collect! {|x| x / v} rows.times do |i| next if i == r v = rary[i][lead] rary[i].each_index {|j| rary[i][j] -= v * rary[r][j]} end lead += 1 end end rary end def convert_to(ary, type) ary.each_with_object([]) do |row, new| new << row.collect {|elem| elem.send(type)} end end class Rational alias _to_s to_s def to_s denominator==1 ? numerator.to_s : _to_s end end def print_matrix(m) max = m[0].collect {-1} m.each {|row| row.each_index {|i| max[i] = [max[i], row[i].to_s.length].max}} m.each {|row| row.each_index {|i| print "% end mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1,-11], [-2, 0, -3, 22] ] print_matrix reduced_row_echelon_form(mtx) puts mtx = [ [ 1, 2, 3, 7], [-4, 7,-2, 7], [ 3, 3, 0, 7] ] reduced = reduced_row_echelon_form(mtx) print_matrix reduced print_matrix convert_to(reduced, :to_f)
Private Function ToReducedRowEchelonForm(M As Variant) As Variant Dim lead As Integer: lead = 0 Dim rowCount As Integer: rowCount = UBound(M) Dim columnCount As Integer: columnCount = UBound(M(0)) Dim i As Integer For r = 0 To rowCount If lead >= columnCount Then Exit For End If i = r Do While M(i)(lead) = 0 i = i + 1 If i = rowCount Then i = r lead = lead + 1 If lead = columnCount Then Exit For End If End If Loop Dim tmp As Variant tmp = M(r) M(r) = M(i) M(i) = tmp If M(r)(lead) <> 0 Then div = M(r)(lead) For t = LBound(M(r)) To UBound(M(r)) M(r)(t) = M(r)(t) / div Next t End If For j = 0 To rowCount If j <> r Then subt = M(j)(lead) For t = LBound(M(j)) To UBound(M(j)) M(j)(t) = M(j)(t) - subt * M(r)(t) Next t End If Next j lead = lead + 1 Next r ToReducedRowEchelonForm = M End Function Public Sub main() r = ToReducedRowEchelonForm(Array( _ Array(1, 2, -1, -4), _ Array(2, 3, -1, -11), _ Array(-2, 0, -3, 22))) For i = LBound(r) To UBound(r) Debug.Print Join(r(i), vbTab) Next i End Sub
Preserve the algorithm and functionality while converting the code from Ruby to Go.
def reduced_row_echelon_form(ary) lead = 0 rows = ary.size cols = ary[0].size rary = convert_to(ary, :to_r) catch :done do rows.times do |r| throw :done if cols <= lead i = r while rary[i][lead] == 0 i += 1 if rows == i i = r lead += 1 throw :done if cols == lead end end rary[i], rary[r] = rary[r], rary[i] v = rary[r][lead] rary[r].collect! {|x| x / v} rows.times do |i| next if i == r v = rary[i][lead] rary[i].each_index {|j| rary[i][j] -= v * rary[r][j]} end lead += 1 end end rary end def convert_to(ary, type) ary.each_with_object([]) do |row, new| new << row.collect {|elem| elem.send(type)} end end class Rational alias _to_s to_s def to_s denominator==1 ? numerator.to_s : _to_s end end def print_matrix(m) max = m[0].collect {-1} m.each {|row| row.each_index {|i| max[i] = [max[i], row[i].to_s.length].max}} m.each {|row| row.each_index {|i| print "% end mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1,-11], [-2, 0, -3, 22] ] print_matrix reduced_row_echelon_form(mtx) puts mtx = [ [ 1, 2, 3, 7], [-4, 7,-2, 7], [ 3, 3, 0, 7] ] reduced = reduced_row_echelon_form(mtx) print_matrix reduced print_matrix convert_to(reduced, :to_f)
package main import "fmt" type matrix [][]float64 func (m matrix) print() { for _, r := range m { fmt.Println(r) } fmt.Println("") } func main() { m := matrix{ { 1, 2, -1, -4}, { 2, 3, -1, -11}, {-2, 0, -3, 22}, } m.print() rref(m) m.print() } func rref(m matrix) { lead := 0 rowCount := len(m) columnCount := len(m[0]) for r := 0; r < rowCount; r++ { if lead >= columnCount { return } i := r for m[i][lead] == 0 { i++ if rowCount == i { i = r lead++ if columnCount == lead { return } } } m[i], m[r] = m[r], m[i] f := 1 / m[r][lead] for j, _ := range m[r] { m[r][j] *= f } for i = 0; i < rowCount; i++ { if i != r { f = m[i][lead] for j, e := range m[r] { m[i][j] -= e * f } } } lead++ } }
Maintain the same structure and functionality when rewriting this code in C.
typealias Matrix = Array<DoubleArray> fun Matrix.toReducedRowEchelonForm() { var lead = 0 val rowCount = this.size val colCount = this[0].size for (r in 0 until rowCount) { if (colCount <= lead) return var i = r while (this[i][lead] == 0.0) { i++ if (rowCount == i) { i = r lead++ if (colCount == lead) return } } val temp = this[i] this[i] = this[r] this[r] = temp if (this[r][lead] != 0.0) { val div = this[r][lead] for (j in 0 until colCount) this[r][j] /= div } for (k in 0 until rowCount) { if (k != r) { val mult = this[k][lead] for (j in 0 until colCount) this[k][j] -= this[r][j] * mult } } lead++ } } fun Matrix.printf(title: String) { println(title) val rowCount = this.size val colCount = this[0].size for (r in 0 until rowCount) { for (c in 0 until colCount) { if (this[r][c] == -0.0) this[r][c] = 0.0 print("${"% 6.2f".format(this[r][c])} ") } println() } println() } fun main(args: Array<String>) { val matrices = listOf( arrayOf( doubleArrayOf( 1.0, 2.0, -1.0, -4.0), doubleArrayOf( 2.0, 3.0, -1.0, -11.0), doubleArrayOf(-2.0, 0.0, -3.0, 22.0) ), arrayOf( doubleArrayOf(1.0, 2.0, 3.0, 4.0, 3.0, 1.0), doubleArrayOf(2.0, 4.0, 6.0, 2.0, 6.0, 2.0), doubleArrayOf(3.0, 6.0, 18.0, 9.0, 9.0, -6.0), doubleArrayOf(4.0, 8.0, 12.0, 10.0, 12.0, 4.0), doubleArrayOf(5.0, 10.0, 24.0, 11.0, 15.0, -4.0) ) ) for (m in matrices) { m.printf("Original matrix:") m.toReducedRowEchelonForm() m.printf("Reduced row echelon form:") } }
#include <stdio.h> #define TALLOC(n,typ) malloc(n*sizeof(typ)) #define EL_Type int typedef struct sMtx { int dim_x, dim_y; EL_Type *m_stor; EL_Type **mtx; } *Matrix, sMatrix; typedef struct sRvec { int dim_x; EL_Type *m_stor; } *RowVec, sRowVec; Matrix NewMatrix( int x_dim, int y_dim ) { int n; Matrix m; m = TALLOC( 1, sMatrix); n = x_dim * y_dim; m->dim_x = x_dim; m->dim_y = y_dim; m->m_stor = TALLOC(n, EL_Type); m->mtx = TALLOC(m->dim_y, EL_Type *); for(n=0; n<y_dim; n++) { m->mtx[n] = m->m_stor+n*x_dim; } return m; } void MtxSetRow(Matrix m, int irow, EL_Type *v) { int ix; EL_Type *mr; mr = m->mtx[irow]; for(ix=0; ix<m->dim_x; ix++) mr[ix] = v[ix]; } Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v) { Matrix m; int iy; m = NewMatrix(x_dim, y_dim); for (iy=0; iy<y_dim; iy++) MtxSetRow(m, iy, v[iy]); return m; } void MtxDisplay( Matrix m ) { int iy, ix; const char *sc; for (iy=0; iy<m->dim_y; iy++) { printf(" "); sc = " "; for (ix=0; ix<m->dim_x; ix++) { printf("%s %3d", sc, m->mtx[iy][ix]); sc = ","; } printf("\n"); } printf("\n"); } void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr) { int ix; EL_Type *drow, *srow; drow = m->mtx[ixrdest]; srow = m->mtx[ixrsrc]; for (ix=0; ix<m->dim_x; ix++) drow[ix] += mplr * srow[ix]; } void MtxSwapRows( Matrix m, int rix1, int rix2) { EL_Type *r1, *r2, temp; int ix; if (rix1 == rix2) return; r1 = m->mtx[rix1]; r2 = m->mtx[rix2]; for (ix=0; ix<m->dim_x; ix++) temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp; } void MtxNormalizeRow( Matrix m, int rix, int lead) { int ix; EL_Type *drow; EL_Type lv; drow = m->mtx[rix]; lv = drow[lead]; for (ix=0; ix<m->dim_x; ix++) drow[ix] /= lv; } #define MtxGet( m, rix, cix ) m->mtx[rix][cix] void MtxToReducedREForm(Matrix m) { int lead; int rix, iix; EL_Type lv; int rowCount = m->dim_y; lead = 0; for (rix=0; rix<rowCount; rix++) { if (lead >= m->dim_x) return; iix = rix; while (0 == MtxGet(m, iix,lead)) { iix++; if (iix == rowCount) { iix = rix; lead++; if (lead == m->dim_x) return; } } MtxSwapRows(m, iix, rix ); MtxNormalizeRow(m, rix, lead ); for (iix=0; iix<rowCount; iix++) { if ( iix != rix ) { lv = MtxGet(m, iix, lead ); MtxMulAndAddRows(m,iix, rix, -lv) ; } } lead++; } } int main() { Matrix m1; static EL_Type r1[] = {1,2,-1,-4}; static EL_Type r2[] = {2,3,-1,-11}; static EL_Type r3[] = {-2,0,-3,22}; static EL_Type *im[] = { r1, r2, r3 }; m1 = InitMatrix( 4,3, im ); printf("Initial\n"); MtxDisplay(m1); MtxToReducedREForm(m1); printf("Reduced R-E form\n"); MtxDisplay(m1); return 0; }
Convert this Scala snippet to C# and keep its semantics consistent.
typealias Matrix = Array<DoubleArray> fun Matrix.toReducedRowEchelonForm() { var lead = 0 val rowCount = this.size val colCount = this[0].size for (r in 0 until rowCount) { if (colCount <= lead) return var i = r while (this[i][lead] == 0.0) { i++ if (rowCount == i) { i = r lead++ if (colCount == lead) return } } val temp = this[i] this[i] = this[r] this[r] = temp if (this[r][lead] != 0.0) { val div = this[r][lead] for (j in 0 until colCount) this[r][j] /= div } for (k in 0 until rowCount) { if (k != r) { val mult = this[k][lead] for (j in 0 until colCount) this[k][j] -= this[r][j] * mult } } lead++ } } fun Matrix.printf(title: String) { println(title) val rowCount = this.size val colCount = this[0].size for (r in 0 until rowCount) { for (c in 0 until colCount) { if (this[r][c] == -0.0) this[r][c] = 0.0 print("${"% 6.2f".format(this[r][c])} ") } println() } println() } fun main(args: Array<String>) { val matrices = listOf( arrayOf( doubleArrayOf( 1.0, 2.0, -1.0, -4.0), doubleArrayOf( 2.0, 3.0, -1.0, -11.0), doubleArrayOf(-2.0, 0.0, -3.0, 22.0) ), arrayOf( doubleArrayOf(1.0, 2.0, 3.0, 4.0, 3.0, 1.0), doubleArrayOf(2.0, 4.0, 6.0, 2.0, 6.0, 2.0), doubleArrayOf(3.0, 6.0, 18.0, 9.0, 9.0, -6.0), doubleArrayOf(4.0, 8.0, 12.0, 10.0, 12.0, 4.0), doubleArrayOf(5.0, 10.0, 24.0, 11.0, 15.0, -4.0) ) ) for (m in matrices) { m.printf("Original matrix:") m.toReducedRowEchelonForm() m.printf("Reduced row echelon form:") } }
using System; namespace rref { class Program { static void Main(string[] args) { int[,] matrix = new int[3, 4]{ { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; matrix = rref(matrix); } private static int[,] rref(int[,] matrix) { int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1); for (int r = 0; r < rowCount; r++) { if (columnCount <= lead) break; int i = r; while (matrix[i, lead] == 0) { i++; if (i == rowCount) { i = r; lead++; if (columnCount == lead) { lead--; break; } } } for (int j = 0; j < columnCount; j++) { int temp = matrix[r, j]; matrix[r, j] = matrix[i, j]; matrix[i, j] = temp; } int div = matrix[r, lead]; if(div != 0) for (int j = 0; j < columnCount; j++) matrix[r, j] /= div; for (int j = 0; j < rowCount; j++) { if (j != r) { int sub = matrix[j, lead]; for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]); } } lead++; } return matrix; } } }
Write the same algorithm in C++ as shown in this Scala implementation.
typealias Matrix = Array<DoubleArray> fun Matrix.toReducedRowEchelonForm() { var lead = 0 val rowCount = this.size val colCount = this[0].size for (r in 0 until rowCount) { if (colCount <= lead) return var i = r while (this[i][lead] == 0.0) { i++ if (rowCount == i) { i = r lead++ if (colCount == lead) return } } val temp = this[i] this[i] = this[r] this[r] = temp if (this[r][lead] != 0.0) { val div = this[r][lead] for (j in 0 until colCount) this[r][j] /= div } for (k in 0 until rowCount) { if (k != r) { val mult = this[k][lead] for (j in 0 until colCount) this[k][j] -= this[r][j] * mult } } lead++ } } fun Matrix.printf(title: String) { println(title) val rowCount = this.size val colCount = this[0].size for (r in 0 until rowCount) { for (c in 0 until colCount) { if (this[r][c] == -0.0) this[r][c] = 0.0 print("${"% 6.2f".format(this[r][c])} ") } println() } println() } fun main(args: Array<String>) { val matrices = listOf( arrayOf( doubleArrayOf( 1.0, 2.0, -1.0, -4.0), doubleArrayOf( 2.0, 3.0, -1.0, -11.0), doubleArrayOf(-2.0, 0.0, -3.0, 22.0) ), arrayOf( doubleArrayOf(1.0, 2.0, 3.0, 4.0, 3.0, 1.0), doubleArrayOf(2.0, 4.0, 6.0, 2.0, 6.0, 2.0), doubleArrayOf(3.0, 6.0, 18.0, 9.0, 9.0, -6.0), doubleArrayOf(4.0, 8.0, 12.0, 10.0, 12.0, 4.0), doubleArrayOf(5.0, 10.0, 24.0, 11.0, 15.0, -4.0) ) ) for (m in matrices) { m.printf("Original matrix:") m.toReducedRowEchelonForm() m.printf("Reduced row echelon form:") } }
#include <algorithm> #include <cstddef> #include <cassert> template<typename MatrixType> struct matrix_traits { typedef typename MatrixType::index_type index_type; typedef typename MatrixType::value_type value_type; static index_type min_row(MatrixType const& A) { return A.min_row(); } static index_type max_row(MatrixType const& A) { return A.max_row(); } static index_type min_column(MatrixType const& A) { return A.min_column(); } static index_type max_column(MatrixType const& A) { return A.max_column(); } static value_type& element(MatrixType& A, index_type i, index_type k) { return A(i,k); } static value_type element(MatrixType const& A, index_type i, index_type k) { return A(i,k); } }; template<typename T, std::size_t rows, std::size_t columns> struct matrix_traits<T[rows][columns]> { typedef std::size_t index_type; typedef T value_type; static index_type min_row(T const (&)[rows][columns]) { return 0; } static index_type max_row(T const (&)[rows][columns]) { return rows-1; } static index_type min_column(T const (&)[rows][columns]) { return 0; } static index_type max_column(T const (&)[rows][columns]) { return columns-1; } static value_type& element(T (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } static value_type element(T const (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } }; template<typename MatrixType> void swap_rows(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) std::swap(mt.element(A, i, col), mt.element(A, k, col)); } template<typename MatrixType> void divide_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(v != 0); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) /= v; } template<typename MatrixType> void add_multiple_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) += v * mt.element(A, k, col); } template<typename MatrixType> void to_reduced_row_echelon_form(MatrixType& A) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; index_type lead = mt.min_row(A); for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row) { if (lead > mt.max_column(A)) return; index_type i = row; while (mt.element(A, i, lead) == 0) { ++i; if (i > mt.max_row(A)) { i = row; ++lead; if (lead > mt.max_column(A)) return; } } swap_rows(A, i, row); divide_row(A, row, mt.element(A, row, lead)); for (i = mt.min_row(A); i <= mt.max_row(A); ++i) { if (i != row) add_multiple_row(A, i, row, -mt.element(A, i, lead)); } } } #include <iostream> int main() { double M[3][4] = { { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; to_reduced_row_echelon_form(M); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) std::cout << M[i][j] << '\t'; std::cout << "\n"; } return EXIT_SUCCESS; }
Convert this Scala snippet to Java and keep its semantics consistent.
typealias Matrix = Array<DoubleArray> fun Matrix.toReducedRowEchelonForm() { var lead = 0 val rowCount = this.size val colCount = this[0].size for (r in 0 until rowCount) { if (colCount <= lead) return var i = r while (this[i][lead] == 0.0) { i++ if (rowCount == i) { i = r lead++ if (colCount == lead) return } } val temp = this[i] this[i] = this[r] this[r] = temp if (this[r][lead] != 0.0) { val div = this[r][lead] for (j in 0 until colCount) this[r][j] /= div } for (k in 0 until rowCount) { if (k != r) { val mult = this[k][lead] for (j in 0 until colCount) this[k][j] -= this[r][j] * mult } } lead++ } } fun Matrix.printf(title: String) { println(title) val rowCount = this.size val colCount = this[0].size for (r in 0 until rowCount) { for (c in 0 until colCount) { if (this[r][c] == -0.0) this[r][c] = 0.0 print("${"% 6.2f".format(this[r][c])} ") } println() } println() } fun main(args: Array<String>) { val matrices = listOf( arrayOf( doubleArrayOf( 1.0, 2.0, -1.0, -4.0), doubleArrayOf( 2.0, 3.0, -1.0, -11.0), doubleArrayOf(-2.0, 0.0, -3.0, 22.0) ), arrayOf( doubleArrayOf(1.0, 2.0, 3.0, 4.0, 3.0, 1.0), doubleArrayOf(2.0, 4.0, 6.0, 2.0, 6.0, 2.0), doubleArrayOf(3.0, 6.0, 18.0, 9.0, 9.0, -6.0), doubleArrayOf(4.0, 8.0, 12.0, 10.0, 12.0, 4.0), doubleArrayOf(5.0, 10.0, 24.0, 11.0, 15.0, -4.0) ) ) for (m in matrices) { m.printf("Original matrix:") m.toReducedRowEchelonForm() m.printf("Reduced row echelon form:") } }
import java.util.*; import java.lang.Math; import org.apache.commons.math.fraction.Fraction; import org.apache.commons.math.fraction.FractionConversionException; class Matrix { LinkedList<LinkedList<Fraction>> matrix; int numRows; int numCols; static class Coordinate { int row; int col; Coordinate(int r, int c) { row = r; col = c; } public String toString() { return "(" + row + ", " + col + ")"; } } Matrix(double [][] m) { numRows = m.length; numCols = m[0].length; matrix = new LinkedList<LinkedList<Fraction>>(); for (int i = 0; i < numRows; i++) { matrix.add(new LinkedList<Fraction>()); for (int j = 0; j < numCols; j++) { try { matrix.get(i).add(new Fraction(m[i][j])); } catch (FractionConversionException e) { System.err.println("Fraction could not be converted from double by apache commons . . ."); } } } } public void Interchange(Coordinate a, Coordinate b) { LinkedList<Fraction> temp = matrix.get(a.row); matrix.set(a.row, matrix.get(b.row)); matrix.set(b.row, temp); int t = a.row; a.row = b.row; b.row = t; } public void Scale(Coordinate x, Fraction d) { LinkedList<Fraction> row = matrix.get(x.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).multiply(d)); } } public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) { LinkedList<Fraction> row = matrix.get(to.row); LinkedList<Fraction> rowMultiplied = matrix.get(from.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar)))); } } public void RREF() { Coordinate pivot = new Coordinate(0,0); int submatrix = 0; for (int x = 0; x < numCols; x++) { pivot = new Coordinate(pivot.row, x); for (int i = x; i < numCols; i++) { if (isColumnZeroes(pivot) == false) { break; } else { pivot.col = i; } } pivot = findPivot(pivot); if (getCoordinate(pivot).doubleValue() == 0.0) { pivot.row++; continue; } if (pivot.row != submatrix) { Interchange(new Coordinate(submatrix, pivot.col), pivot); } if (getCoordinate(pivot).doubleValue() != 1) { Fraction scalar = getCoordinate(pivot).reciprocal(); Scale(pivot, scalar); } for (int i = pivot.row; i < numRows; i++) { if (i == pivot.row) { continue; } Coordinate belowPivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(belowPivot, pivot, complement); } for (int i = pivot.row; i >= 0; i--) { if (i == pivot.row) { if (getCoordinate(pivot).doubleValue() != 1.0) { Scale(pivot, getCoordinate(pivot).reciprocal()); } continue; } if (i == pivot.row) { continue; } Coordinate abovePivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(abovePivot, pivot, complement); } if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) { break; } submatrix++; pivot.row++; } } public boolean isColumnZeroes(Coordinate a) { for (int i = 0; i < numRows; i++) { if (matrix.get(i).get(a.col).doubleValue() != 0.0) { return false; } } return true; } public boolean isRowZeroes(Coordinate a) { for (int i = 0; i < numCols; i++) { if (matrix.get(a.row).get(i).doubleValue() != 0.0) { return false; } } return true; } public Coordinate findPivot(Coordinate a) { int first_row = a.row; Coordinate pivot = new Coordinate(a.row, a.col); Coordinate current = new Coordinate(a.row, a.col); for (int i = a.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() == 1.0) { Interchange(current, a); } } current.row = a.row; for (int i = current.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() != 0) { pivot.row = i; break; } } return pivot; } public Fraction getCoordinate(Coordinate a) { return matrix.get(a.row).get(a.col); } public String toString() { return matrix.toString().replace("], ", "]\n"); } public static void main (String[] args) { double[][] matrix_1 = { {1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22} }; Matrix x = new Matrix(matrix_1); System.out.println("before\n" + x.toString() + "\n"); x.RREF(); System.out.println("after\n" + x.toString() + "\n"); double matrix_2 [][] = { {2, 0, -1, 0, 0}, {1, 0, 0, -1, 0}, {3, 0, 0, -2, -1}, {0, 1, 0, 0, -2}, {0, 1, -1, 0, 0} }; Matrix y = new Matrix(matrix_2); System.out.println("before\n" + y.toString() + "\n"); y.RREF(); System.out.println("after\n" + y.toString() + "\n"); double matrix_3 [][] = { {1, 2, 3, 4, 3, 1}, {2, 4, 6, 2, 6, 2}, {3, 6, 18, 9, 9, -6}, {4, 8, 12, 10, 12, 4}, {5, 10, 24, 11, 15, -4} }; Matrix z = new Matrix(matrix_3); System.out.println("before\n" + z.toString() + "\n"); z.RREF(); System.out.println("after\n" + z.toString() + "\n"); double matrix_4 [][] = { {0, 1}, {1, 2}, {0,5} }; Matrix a = new Matrix(matrix_4); System.out.println("before\n" + a.toString() + "\n"); a.RREF(); System.out.println("after\n" + a.toString() + "\n"); } }
Maintain the same structure and functionality when rewriting this code in Python.
typealias Matrix = Array<DoubleArray> fun Matrix.toReducedRowEchelonForm() { var lead = 0 val rowCount = this.size val colCount = this[0].size for (r in 0 until rowCount) { if (colCount <= lead) return var i = r while (this[i][lead] == 0.0) { i++ if (rowCount == i) { i = r lead++ if (colCount == lead) return } } val temp = this[i] this[i] = this[r] this[r] = temp if (this[r][lead] != 0.0) { val div = this[r][lead] for (j in 0 until colCount) this[r][j] /= div } for (k in 0 until rowCount) { if (k != r) { val mult = this[k][lead] for (j in 0 until colCount) this[k][j] -= this[r][j] * mult } } lead++ } } fun Matrix.printf(title: String) { println(title) val rowCount = this.size val colCount = this[0].size for (r in 0 until rowCount) { for (c in 0 until colCount) { if (this[r][c] == -0.0) this[r][c] = 0.0 print("${"% 6.2f".format(this[r][c])} ") } println() } println() } fun main(args: Array<String>) { val matrices = listOf( arrayOf( doubleArrayOf( 1.0, 2.0, -1.0, -4.0), doubleArrayOf( 2.0, 3.0, -1.0, -11.0), doubleArrayOf(-2.0, 0.0, -3.0, 22.0) ), arrayOf( doubleArrayOf(1.0, 2.0, 3.0, 4.0, 3.0, 1.0), doubleArrayOf(2.0, 4.0, 6.0, 2.0, 6.0, 2.0), doubleArrayOf(3.0, 6.0, 18.0, 9.0, 9.0, -6.0), doubleArrayOf(4.0, 8.0, 12.0, 10.0, 12.0, 4.0), doubleArrayOf(5.0, 10.0, 24.0, 11.0, 15.0, -4.0) ) ) for (m in matrices) { m.printf("Original matrix:") m.toReducedRowEchelonForm() m.printf("Reduced row echelon form:") } }
def ToReducedRowEchelonForm( M): if not M: return lead = 0 rowCount = len(M) columnCount = len(M[0]) for r in range(rowCount): if lead >= columnCount: return i = r while M[i][lead] == 0: i += 1 if i == rowCount: i = r lead += 1 if columnCount == lead: return M[i],M[r] = M[r],M[i] lv = M[r][lead] M[r] = [ mrx / float(lv) for mrx in M[r]] for i in range(rowCount): if i != r: lv = M[i][lead] M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])] lead += 1 mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22],] ToReducedRowEchelonForm( mtx ) for rw in mtx: print ', '.join( (str(rv) for rv in rw) )
Transform the following Scala implementation into VB, maintaining the same output and logic.
typealias Matrix = Array<DoubleArray> fun Matrix.toReducedRowEchelonForm() { var lead = 0 val rowCount = this.size val colCount = this[0].size for (r in 0 until rowCount) { if (colCount <= lead) return var i = r while (this[i][lead] == 0.0) { i++ if (rowCount == i) { i = r lead++ if (colCount == lead) return } } val temp = this[i] this[i] = this[r] this[r] = temp if (this[r][lead] != 0.0) { val div = this[r][lead] for (j in 0 until colCount) this[r][j] /= div } for (k in 0 until rowCount) { if (k != r) { val mult = this[k][lead] for (j in 0 until colCount) this[k][j] -= this[r][j] * mult } } lead++ } } fun Matrix.printf(title: String) { println(title) val rowCount = this.size val colCount = this[0].size for (r in 0 until rowCount) { for (c in 0 until colCount) { if (this[r][c] == -0.0) this[r][c] = 0.0 print("${"% 6.2f".format(this[r][c])} ") } println() } println() } fun main(args: Array<String>) { val matrices = listOf( arrayOf( doubleArrayOf( 1.0, 2.0, -1.0, -4.0), doubleArrayOf( 2.0, 3.0, -1.0, -11.0), doubleArrayOf(-2.0, 0.0, -3.0, 22.0) ), arrayOf( doubleArrayOf(1.0, 2.0, 3.0, 4.0, 3.0, 1.0), doubleArrayOf(2.0, 4.0, 6.0, 2.0, 6.0, 2.0), doubleArrayOf(3.0, 6.0, 18.0, 9.0, 9.0, -6.0), doubleArrayOf(4.0, 8.0, 12.0, 10.0, 12.0, 4.0), doubleArrayOf(5.0, 10.0, 24.0, 11.0, 15.0, -4.0) ) ) for (m in matrices) { m.printf("Original matrix:") m.toReducedRowEchelonForm() m.printf("Reduced row echelon form:") } }
Private Function ToReducedRowEchelonForm(M As Variant) As Variant Dim lead As Integer: lead = 0 Dim rowCount As Integer: rowCount = UBound(M) Dim columnCount As Integer: columnCount = UBound(M(0)) Dim i As Integer For r = 0 To rowCount If lead >= columnCount Then Exit For End If i = r Do While M(i)(lead) = 0 i = i + 1 If i = rowCount Then i = r lead = lead + 1 If lead = columnCount Then Exit For End If End If Loop Dim tmp As Variant tmp = M(r) M(r) = M(i) M(i) = tmp If M(r)(lead) <> 0 Then div = M(r)(lead) For t = LBound(M(r)) To UBound(M(r)) M(r)(t) = M(r)(t) / div Next t End If For j = 0 To rowCount If j <> r Then subt = M(j)(lead) For t = LBound(M(j)) To UBound(M(j)) M(j)(t) = M(j)(t) - subt * M(r)(t) Next t End If Next j lead = lead + 1 Next r ToReducedRowEchelonForm = M End Function Public Sub main() r = ToReducedRowEchelonForm(Array( _ Array(1, 2, -1, -4), _ Array(2, 3, -1, -11), _ Array(-2, 0, -3, 22))) For i = LBound(r) To UBound(r) Debug.Print Join(r(i), vbTab) Next i End Sub
Convert this Scala snippet to Go and keep its semantics consistent.
typealias Matrix = Array<DoubleArray> fun Matrix.toReducedRowEchelonForm() { var lead = 0 val rowCount = this.size val colCount = this[0].size for (r in 0 until rowCount) { if (colCount <= lead) return var i = r while (this[i][lead] == 0.0) { i++ if (rowCount == i) { i = r lead++ if (colCount == lead) return } } val temp = this[i] this[i] = this[r] this[r] = temp if (this[r][lead] != 0.0) { val div = this[r][lead] for (j in 0 until colCount) this[r][j] /= div } for (k in 0 until rowCount) { if (k != r) { val mult = this[k][lead] for (j in 0 until colCount) this[k][j] -= this[r][j] * mult } } lead++ } } fun Matrix.printf(title: String) { println(title) val rowCount = this.size val colCount = this[0].size for (r in 0 until rowCount) { for (c in 0 until colCount) { if (this[r][c] == -0.0) this[r][c] = 0.0 print("${"% 6.2f".format(this[r][c])} ") } println() } println() } fun main(args: Array<String>) { val matrices = listOf( arrayOf( doubleArrayOf( 1.0, 2.0, -1.0, -4.0), doubleArrayOf( 2.0, 3.0, -1.0, -11.0), doubleArrayOf(-2.0, 0.0, -3.0, 22.0) ), arrayOf( doubleArrayOf(1.0, 2.0, 3.0, 4.0, 3.0, 1.0), doubleArrayOf(2.0, 4.0, 6.0, 2.0, 6.0, 2.0), doubleArrayOf(3.0, 6.0, 18.0, 9.0, 9.0, -6.0), doubleArrayOf(4.0, 8.0, 12.0, 10.0, 12.0, 4.0), doubleArrayOf(5.0, 10.0, 24.0, 11.0, 15.0, -4.0) ) ) for (m in matrices) { m.printf("Original matrix:") m.toReducedRowEchelonForm() m.printf("Reduced row echelon form:") } }
package main import "fmt" type matrix [][]float64 func (m matrix) print() { for _, r := range m { fmt.Println(r) } fmt.Println("") } func main() { m := matrix{ { 1, 2, -1, -4}, { 2, 3, -1, -11}, {-2, 0, -3, 22}, } m.print() rref(m) m.print() } func rref(m matrix) { lead := 0 rowCount := len(m) columnCount := len(m[0]) for r := 0; r < rowCount; r++ { if lead >= columnCount { return } i := r for m[i][lead] == 0 { i++ if rowCount == i { i = r lead++ if columnCount == lead { return } } } m[i], m[r] = m[r], m[i] f := 1 / m[r][lead] for j, _ := range m[r] { m[r][j] *= f } for i = 0; i < rowCount; i++ { if i != r { f = m[i][lead] for j, e := range m[r] { m[i][j] -= e * f } } } lead++ } }
Can you help me rewrite this code in C instead of Swift, keeping it the same logically?
var lead = 0 for r in 0..<rows { if (cols <= lead) { break } var i = r while (m[i][lead] == 0) { i += 1 if (i == rows) { i = r lead += 1 if (cols == lead) { lead -= 1 break } } } for j in 0..<cols { let temp = m[r][j] m[r][j] = m[i][j] m[i][j] = temp } let div = m[r][lead] if (div != 0) { for j in 0..<cols { m[r][j] /= div } } for j in 0..<rows { if (j != r) { let sub = m[j][lead] for k in 0..<cols { m[j][k] -= (sub * m[r][k]) } } } lead += 1 }
#include <stdio.h> #define TALLOC(n,typ) malloc(n*sizeof(typ)) #define EL_Type int typedef struct sMtx { int dim_x, dim_y; EL_Type *m_stor; EL_Type **mtx; } *Matrix, sMatrix; typedef struct sRvec { int dim_x; EL_Type *m_stor; } *RowVec, sRowVec; Matrix NewMatrix( int x_dim, int y_dim ) { int n; Matrix m; m = TALLOC( 1, sMatrix); n = x_dim * y_dim; m->dim_x = x_dim; m->dim_y = y_dim; m->m_stor = TALLOC(n, EL_Type); m->mtx = TALLOC(m->dim_y, EL_Type *); for(n=0; n<y_dim; n++) { m->mtx[n] = m->m_stor+n*x_dim; } return m; } void MtxSetRow(Matrix m, int irow, EL_Type *v) { int ix; EL_Type *mr; mr = m->mtx[irow]; for(ix=0; ix<m->dim_x; ix++) mr[ix] = v[ix]; } Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v) { Matrix m; int iy; m = NewMatrix(x_dim, y_dim); for (iy=0; iy<y_dim; iy++) MtxSetRow(m, iy, v[iy]); return m; } void MtxDisplay( Matrix m ) { int iy, ix; const char *sc; for (iy=0; iy<m->dim_y; iy++) { printf(" "); sc = " "; for (ix=0; ix<m->dim_x; ix++) { printf("%s %3d", sc, m->mtx[iy][ix]); sc = ","; } printf("\n"); } printf("\n"); } void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr) { int ix; EL_Type *drow, *srow; drow = m->mtx[ixrdest]; srow = m->mtx[ixrsrc]; for (ix=0; ix<m->dim_x; ix++) drow[ix] += mplr * srow[ix]; } void MtxSwapRows( Matrix m, int rix1, int rix2) { EL_Type *r1, *r2, temp; int ix; if (rix1 == rix2) return; r1 = m->mtx[rix1]; r2 = m->mtx[rix2]; for (ix=0; ix<m->dim_x; ix++) temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp; } void MtxNormalizeRow( Matrix m, int rix, int lead) { int ix; EL_Type *drow; EL_Type lv; drow = m->mtx[rix]; lv = drow[lead]; for (ix=0; ix<m->dim_x; ix++) drow[ix] /= lv; } #define MtxGet( m, rix, cix ) m->mtx[rix][cix] void MtxToReducedREForm(Matrix m) { int lead; int rix, iix; EL_Type lv; int rowCount = m->dim_y; lead = 0; for (rix=0; rix<rowCount; rix++) { if (lead >= m->dim_x) return; iix = rix; while (0 == MtxGet(m, iix,lead)) { iix++; if (iix == rowCount) { iix = rix; lead++; if (lead == m->dim_x) return; } } MtxSwapRows(m, iix, rix ); MtxNormalizeRow(m, rix, lead ); for (iix=0; iix<rowCount; iix++) { if ( iix != rix ) { lv = MtxGet(m, iix, lead ); MtxMulAndAddRows(m,iix, rix, -lv) ; } } lead++; } } int main() { Matrix m1; static EL_Type r1[] = {1,2,-1,-4}; static EL_Type r2[] = {2,3,-1,-11}; static EL_Type r3[] = {-2,0,-3,22}; static EL_Type *im[] = { r1, r2, r3 }; m1 = InitMatrix( 4,3, im ); printf("Initial\n"); MtxDisplay(m1); MtxToReducedREForm(m1); printf("Reduced R-E form\n"); MtxDisplay(m1); return 0; }
Generate a C# translation of this Swift snippet without changing its computational steps.
var lead = 0 for r in 0..<rows { if (cols <= lead) { break } var i = r while (m[i][lead] == 0) { i += 1 if (i == rows) { i = r lead += 1 if (cols == lead) { lead -= 1 break } } } for j in 0..<cols { let temp = m[r][j] m[r][j] = m[i][j] m[i][j] = temp } let div = m[r][lead] if (div != 0) { for j in 0..<cols { m[r][j] /= div } } for j in 0..<rows { if (j != r) { let sub = m[j][lead] for k in 0..<cols { m[j][k] -= (sub * m[r][k]) } } } lead += 1 }
using System; namespace rref { class Program { static void Main(string[] args) { int[,] matrix = new int[3, 4]{ { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; matrix = rref(matrix); } private static int[,] rref(int[,] matrix) { int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1); for (int r = 0; r < rowCount; r++) { if (columnCount <= lead) break; int i = r; while (matrix[i, lead] == 0) { i++; if (i == rowCount) { i = r; lead++; if (columnCount == lead) { lead--; break; } } } for (int j = 0; j < columnCount; j++) { int temp = matrix[r, j]; matrix[r, j] = matrix[i, j]; matrix[i, j] = temp; } int div = matrix[r, lead]; if(div != 0) for (int j = 0; j < columnCount; j++) matrix[r, j] /= div; for (int j = 0; j < rowCount; j++) { if (j != r) { int sub = matrix[j, lead]; for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]); } } lead++; } return matrix; } } }
Convert this Swift block to C++, preserving its control flow and logic.
var lead = 0 for r in 0..<rows { if (cols <= lead) { break } var i = r while (m[i][lead] == 0) { i += 1 if (i == rows) { i = r lead += 1 if (cols == lead) { lead -= 1 break } } } for j in 0..<cols { let temp = m[r][j] m[r][j] = m[i][j] m[i][j] = temp } let div = m[r][lead] if (div != 0) { for j in 0..<cols { m[r][j] /= div } } for j in 0..<rows { if (j != r) { let sub = m[j][lead] for k in 0..<cols { m[j][k] -= (sub * m[r][k]) } } } lead += 1 }
#include <algorithm> #include <cstddef> #include <cassert> template<typename MatrixType> struct matrix_traits { typedef typename MatrixType::index_type index_type; typedef typename MatrixType::value_type value_type; static index_type min_row(MatrixType const& A) { return A.min_row(); } static index_type max_row(MatrixType const& A) { return A.max_row(); } static index_type min_column(MatrixType const& A) { return A.min_column(); } static index_type max_column(MatrixType const& A) { return A.max_column(); } static value_type& element(MatrixType& A, index_type i, index_type k) { return A(i,k); } static value_type element(MatrixType const& A, index_type i, index_type k) { return A(i,k); } }; template<typename T, std::size_t rows, std::size_t columns> struct matrix_traits<T[rows][columns]> { typedef std::size_t index_type; typedef T value_type; static index_type min_row(T const (&)[rows][columns]) { return 0; } static index_type max_row(T const (&)[rows][columns]) { return rows-1; } static index_type min_column(T const (&)[rows][columns]) { return 0; } static index_type max_column(T const (&)[rows][columns]) { return columns-1; } static value_type& element(T (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } static value_type element(T const (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } }; template<typename MatrixType> void swap_rows(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) std::swap(mt.element(A, i, col), mt.element(A, k, col)); } template<typename MatrixType> void divide_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(v != 0); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) /= v; } template<typename MatrixType> void add_multiple_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) += v * mt.element(A, k, col); } template<typename MatrixType> void to_reduced_row_echelon_form(MatrixType& A) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; index_type lead = mt.min_row(A); for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row) { if (lead > mt.max_column(A)) return; index_type i = row; while (mt.element(A, i, lead) == 0) { ++i; if (i > mt.max_row(A)) { i = row; ++lead; if (lead > mt.max_column(A)) return; } } swap_rows(A, i, row); divide_row(A, row, mt.element(A, row, lead)); for (i = mt.min_row(A); i <= mt.max_row(A); ++i) { if (i != row) add_multiple_row(A, i, row, -mt.element(A, i, lead)); } } } #include <iostream> int main() { double M[3][4] = { { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; to_reduced_row_echelon_form(M); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) std::cout << M[i][j] << '\t'; std::cout << "\n"; } return EXIT_SUCCESS; }
Please provide an equivalent version of this Swift code in Java.
var lead = 0 for r in 0..<rows { if (cols <= lead) { break } var i = r while (m[i][lead] == 0) { i += 1 if (i == rows) { i = r lead += 1 if (cols == lead) { lead -= 1 break } } } for j in 0..<cols { let temp = m[r][j] m[r][j] = m[i][j] m[i][j] = temp } let div = m[r][lead] if (div != 0) { for j in 0..<cols { m[r][j] /= div } } for j in 0..<rows { if (j != r) { let sub = m[j][lead] for k in 0..<cols { m[j][k] -= (sub * m[r][k]) } } } lead += 1 }
import java.util.*; import java.lang.Math; import org.apache.commons.math.fraction.Fraction; import org.apache.commons.math.fraction.FractionConversionException; class Matrix { LinkedList<LinkedList<Fraction>> matrix; int numRows; int numCols; static class Coordinate { int row; int col; Coordinate(int r, int c) { row = r; col = c; } public String toString() { return "(" + row + ", " + col + ")"; } } Matrix(double [][] m) { numRows = m.length; numCols = m[0].length; matrix = new LinkedList<LinkedList<Fraction>>(); for (int i = 0; i < numRows; i++) { matrix.add(new LinkedList<Fraction>()); for (int j = 0; j < numCols; j++) { try { matrix.get(i).add(new Fraction(m[i][j])); } catch (FractionConversionException e) { System.err.println("Fraction could not be converted from double by apache commons . . ."); } } } } public void Interchange(Coordinate a, Coordinate b) { LinkedList<Fraction> temp = matrix.get(a.row); matrix.set(a.row, matrix.get(b.row)); matrix.set(b.row, temp); int t = a.row; a.row = b.row; b.row = t; } public void Scale(Coordinate x, Fraction d) { LinkedList<Fraction> row = matrix.get(x.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).multiply(d)); } } public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) { LinkedList<Fraction> row = matrix.get(to.row); LinkedList<Fraction> rowMultiplied = matrix.get(from.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar)))); } } public void RREF() { Coordinate pivot = new Coordinate(0,0); int submatrix = 0; for (int x = 0; x < numCols; x++) { pivot = new Coordinate(pivot.row, x); for (int i = x; i < numCols; i++) { if (isColumnZeroes(pivot) == false) { break; } else { pivot.col = i; } } pivot = findPivot(pivot); if (getCoordinate(pivot).doubleValue() == 0.0) { pivot.row++; continue; } if (pivot.row != submatrix) { Interchange(new Coordinate(submatrix, pivot.col), pivot); } if (getCoordinate(pivot).doubleValue() != 1) { Fraction scalar = getCoordinate(pivot).reciprocal(); Scale(pivot, scalar); } for (int i = pivot.row; i < numRows; i++) { if (i == pivot.row) { continue; } Coordinate belowPivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(belowPivot, pivot, complement); } for (int i = pivot.row; i >= 0; i--) { if (i == pivot.row) { if (getCoordinate(pivot).doubleValue() != 1.0) { Scale(pivot, getCoordinate(pivot).reciprocal()); } continue; } if (i == pivot.row) { continue; } Coordinate abovePivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(abovePivot, pivot, complement); } if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) { break; } submatrix++; pivot.row++; } } public boolean isColumnZeroes(Coordinate a) { for (int i = 0; i < numRows; i++) { if (matrix.get(i).get(a.col).doubleValue() != 0.0) { return false; } } return true; } public boolean isRowZeroes(Coordinate a) { for (int i = 0; i < numCols; i++) { if (matrix.get(a.row).get(i).doubleValue() != 0.0) { return false; } } return true; } public Coordinate findPivot(Coordinate a) { int first_row = a.row; Coordinate pivot = new Coordinate(a.row, a.col); Coordinate current = new Coordinate(a.row, a.col); for (int i = a.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() == 1.0) { Interchange(current, a); } } current.row = a.row; for (int i = current.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() != 0) { pivot.row = i; break; } } return pivot; } public Fraction getCoordinate(Coordinate a) { return matrix.get(a.row).get(a.col); } public String toString() { return matrix.toString().replace("], ", "]\n"); } public static void main (String[] args) { double[][] matrix_1 = { {1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22} }; Matrix x = new Matrix(matrix_1); System.out.println("before\n" + x.toString() + "\n"); x.RREF(); System.out.println("after\n" + x.toString() + "\n"); double matrix_2 [][] = { {2, 0, -1, 0, 0}, {1, 0, 0, -1, 0}, {3, 0, 0, -2, -1}, {0, 1, 0, 0, -2}, {0, 1, -1, 0, 0} }; Matrix y = new Matrix(matrix_2); System.out.println("before\n" + y.toString() + "\n"); y.RREF(); System.out.println("after\n" + y.toString() + "\n"); double matrix_3 [][] = { {1, 2, 3, 4, 3, 1}, {2, 4, 6, 2, 6, 2}, {3, 6, 18, 9, 9, -6}, {4, 8, 12, 10, 12, 4}, {5, 10, 24, 11, 15, -4} }; Matrix z = new Matrix(matrix_3); System.out.println("before\n" + z.toString() + "\n"); z.RREF(); System.out.println("after\n" + z.toString() + "\n"); double matrix_4 [][] = { {0, 1}, {1, 2}, {0,5} }; Matrix a = new Matrix(matrix_4); System.out.println("before\n" + a.toString() + "\n"); a.RREF(); System.out.println("after\n" + a.toString() + "\n"); } }
Produce a functionally identical Python code for the snippet given in Swift.
var lead = 0 for r in 0..<rows { if (cols <= lead) { break } var i = r while (m[i][lead] == 0) { i += 1 if (i == rows) { i = r lead += 1 if (cols == lead) { lead -= 1 break } } } for j in 0..<cols { let temp = m[r][j] m[r][j] = m[i][j] m[i][j] = temp } let div = m[r][lead] if (div != 0) { for j in 0..<cols { m[r][j] /= div } } for j in 0..<rows { if (j != r) { let sub = m[j][lead] for k in 0..<cols { m[j][k] -= (sub * m[r][k]) } } } lead += 1 }
def ToReducedRowEchelonForm( M): if not M: return lead = 0 rowCount = len(M) columnCount = len(M[0]) for r in range(rowCount): if lead >= columnCount: return i = r while M[i][lead] == 0: i += 1 if i == rowCount: i = r lead += 1 if columnCount == lead: return M[i],M[r] = M[r],M[i] lv = M[r][lead] M[r] = [ mrx / float(lv) for mrx in M[r]] for i in range(rowCount): if i != r: lv = M[i][lead] M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])] lead += 1 mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22],] ToReducedRowEchelonForm( mtx ) for rw in mtx: print ', '.join( (str(rv) for rv in rw) )
Rewrite the snippet below in VB so it works the same as the original Swift code.
var lead = 0 for r in 0..<rows { if (cols <= lead) { break } var i = r while (m[i][lead] == 0) { i += 1 if (i == rows) { i = r lead += 1 if (cols == lead) { lead -= 1 break } } } for j in 0..<cols { let temp = m[r][j] m[r][j] = m[i][j] m[i][j] = temp } let div = m[r][lead] if (div != 0) { for j in 0..<cols { m[r][j] /= div } } for j in 0..<rows { if (j != r) { let sub = m[j][lead] for k in 0..<cols { m[j][k] -= (sub * m[r][k]) } } } lead += 1 }
Private Function ToReducedRowEchelonForm(M As Variant) As Variant Dim lead As Integer: lead = 0 Dim rowCount As Integer: rowCount = UBound(M) Dim columnCount As Integer: columnCount = UBound(M(0)) Dim i As Integer For r = 0 To rowCount If lead >= columnCount Then Exit For End If i = r Do While M(i)(lead) = 0 i = i + 1 If i = rowCount Then i = r lead = lead + 1 If lead = columnCount Then Exit For End If End If Loop Dim tmp As Variant tmp = M(r) M(r) = M(i) M(i) = tmp If M(r)(lead) <> 0 Then div = M(r)(lead) For t = LBound(M(r)) To UBound(M(r)) M(r)(t) = M(r)(t) / div Next t End If For j = 0 To rowCount If j <> r Then subt = M(j)(lead) For t = LBound(M(j)) To UBound(M(j)) M(j)(t) = M(j)(t) - subt * M(r)(t) Next t End If Next j lead = lead + 1 Next r ToReducedRowEchelonForm = M End Function Public Sub main() r = ToReducedRowEchelonForm(Array( _ Array(1, 2, -1, -4), _ Array(2, 3, -1, -11), _ Array(-2, 0, -3, 22))) For i = LBound(r) To UBound(r) Debug.Print Join(r(i), vbTab) Next i End Sub
Write the same algorithm in Go as shown in this Swift implementation.
var lead = 0 for r in 0..<rows { if (cols <= lead) { break } var i = r while (m[i][lead] == 0) { i += 1 if (i == rows) { i = r lead += 1 if (cols == lead) { lead -= 1 break } } } for j in 0..<cols { let temp = m[r][j] m[r][j] = m[i][j] m[i][j] = temp } let div = m[r][lead] if (div != 0) { for j in 0..<cols { m[r][j] /= div } } for j in 0..<rows { if (j != r) { let sub = m[j][lead] for k in 0..<cols { m[j][k] -= (sub * m[r][k]) } } } lead += 1 }
package main import "fmt" type matrix [][]float64 func (m matrix) print() { for _, r := range m { fmt.Println(r) } fmt.Println("") } func main() { m := matrix{ { 1, 2, -1, -4}, { 2, 3, -1, -11}, {-2, 0, -3, 22}, } m.print() rref(m) m.print() } func rref(m matrix) { lead := 0 rowCount := len(m) columnCount := len(m[0]) for r := 0; r < rowCount; r++ { if lead >= columnCount { return } i := r for m[i][lead] == 0 { i++ if rowCount == i { i = r lead++ if columnCount == lead { return } } } m[i], m[r] = m[r], m[i] f := 1 / m[r][lead] for j, _ := range m[r] { m[r][j] *= f } for i = 0; i < rowCount; i++ { if i != r { f = m[i][lead] for j, e := range m[r] { m[i][j] -= e * f } } } lead++ } }
Preserve the algorithm and functionality while converting the code from Tcl to C.
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc} proc toRREF {m} { set lead 0 lassign [size $m] rows cols for {set r 0} {$r < $rows} {incr r} { if {$cols <= $lead} { break } set i $r while {[lindex $m $i $lead] == 0} { incr i if {$rows == $i} { set i $r incr lead if {$cols == $lead} { return $m } } } foreach idx [list $i $r] row [list [lindex $m $r] [lindex $m $i]] { lset m $idx $row } set val [lindex $m $r $lead] for {set j 0} {$j < $cols} {incr j} { lset m $r $j [/ [double [lindex $m $r $j]] $val] } for {set i 0} {$i < $rows} {incr i} { if {$i != $r} { set val [lindex $m $i $lead] for {set j 0} {$j < $cols} {incr j} { lset m $i $j [- [lindex $m $i $j] [* $val [lindex $m $r $j]]] } } } incr lead } return $m } set m {{1 2 -1 -4} {2 3 -1 -11} {-2 0 -3 22}} print_matrix $m print_matrix [toRREF $m]
#include <stdio.h> #define TALLOC(n,typ) malloc(n*sizeof(typ)) #define EL_Type int typedef struct sMtx { int dim_x, dim_y; EL_Type *m_stor; EL_Type **mtx; } *Matrix, sMatrix; typedef struct sRvec { int dim_x; EL_Type *m_stor; } *RowVec, sRowVec; Matrix NewMatrix( int x_dim, int y_dim ) { int n; Matrix m; m = TALLOC( 1, sMatrix); n = x_dim * y_dim; m->dim_x = x_dim; m->dim_y = y_dim; m->m_stor = TALLOC(n, EL_Type); m->mtx = TALLOC(m->dim_y, EL_Type *); for(n=0; n<y_dim; n++) { m->mtx[n] = m->m_stor+n*x_dim; } return m; } void MtxSetRow(Matrix m, int irow, EL_Type *v) { int ix; EL_Type *mr; mr = m->mtx[irow]; for(ix=0; ix<m->dim_x; ix++) mr[ix] = v[ix]; } Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v) { Matrix m; int iy; m = NewMatrix(x_dim, y_dim); for (iy=0; iy<y_dim; iy++) MtxSetRow(m, iy, v[iy]); return m; } void MtxDisplay( Matrix m ) { int iy, ix; const char *sc; for (iy=0; iy<m->dim_y; iy++) { printf(" "); sc = " "; for (ix=0; ix<m->dim_x; ix++) { printf("%s %3d", sc, m->mtx[iy][ix]); sc = ","; } printf("\n"); } printf("\n"); } void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr) { int ix; EL_Type *drow, *srow; drow = m->mtx[ixrdest]; srow = m->mtx[ixrsrc]; for (ix=0; ix<m->dim_x; ix++) drow[ix] += mplr * srow[ix]; } void MtxSwapRows( Matrix m, int rix1, int rix2) { EL_Type *r1, *r2, temp; int ix; if (rix1 == rix2) return; r1 = m->mtx[rix1]; r2 = m->mtx[rix2]; for (ix=0; ix<m->dim_x; ix++) temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp; } void MtxNormalizeRow( Matrix m, int rix, int lead) { int ix; EL_Type *drow; EL_Type lv; drow = m->mtx[rix]; lv = drow[lead]; for (ix=0; ix<m->dim_x; ix++) drow[ix] /= lv; } #define MtxGet( m, rix, cix ) m->mtx[rix][cix] void MtxToReducedREForm(Matrix m) { int lead; int rix, iix; EL_Type lv; int rowCount = m->dim_y; lead = 0; for (rix=0; rix<rowCount; rix++) { if (lead >= m->dim_x) return; iix = rix; while (0 == MtxGet(m, iix,lead)) { iix++; if (iix == rowCount) { iix = rix; lead++; if (lead == m->dim_x) return; } } MtxSwapRows(m, iix, rix ); MtxNormalizeRow(m, rix, lead ); for (iix=0; iix<rowCount; iix++) { if ( iix != rix ) { lv = MtxGet(m, iix, lead ); MtxMulAndAddRows(m,iix, rix, -lv) ; } } lead++; } } int main() { Matrix m1; static EL_Type r1[] = {1,2,-1,-4}; static EL_Type r2[] = {2,3,-1,-11}; static EL_Type r3[] = {-2,0,-3,22}; static EL_Type *im[] = { r1, r2, r3 }; m1 = InitMatrix( 4,3, im ); printf("Initial\n"); MtxDisplay(m1); MtxToReducedREForm(m1); printf("Reduced R-E form\n"); MtxDisplay(m1); return 0; }
Keep all operations the same but rewrite the snippet in C#.
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc} proc toRREF {m} { set lead 0 lassign [size $m] rows cols for {set r 0} {$r < $rows} {incr r} { if {$cols <= $lead} { break } set i $r while {[lindex $m $i $lead] == 0} { incr i if {$rows == $i} { set i $r incr lead if {$cols == $lead} { return $m } } } foreach idx [list $i $r] row [list [lindex $m $r] [lindex $m $i]] { lset m $idx $row } set val [lindex $m $r $lead] for {set j 0} {$j < $cols} {incr j} { lset m $r $j [/ [double [lindex $m $r $j]] $val] } for {set i 0} {$i < $rows} {incr i} { if {$i != $r} { set val [lindex $m $i $lead] for {set j 0} {$j < $cols} {incr j} { lset m $i $j [- [lindex $m $i $j] [* $val [lindex $m $r $j]]] } } } incr lead } return $m } set m {{1 2 -1 -4} {2 3 -1 -11} {-2 0 -3 22}} print_matrix $m print_matrix [toRREF $m]
using System; namespace rref { class Program { static void Main(string[] args) { int[,] matrix = new int[3, 4]{ { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; matrix = rref(matrix); } private static int[,] rref(int[,] matrix) { int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1); for (int r = 0; r < rowCount; r++) { if (columnCount <= lead) break; int i = r; while (matrix[i, lead] == 0) { i++; if (i == rowCount) { i = r; lead++; if (columnCount == lead) { lead--; break; } } } for (int j = 0; j < columnCount; j++) { int temp = matrix[r, j]; matrix[r, j] = matrix[i, j]; matrix[i, j] = temp; } int div = matrix[r, lead]; if(div != 0) for (int j = 0; j < columnCount; j++) matrix[r, j] /= div; for (int j = 0; j < rowCount; j++) { if (j != r) { int sub = matrix[j, lead]; for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]); } } lead++; } return matrix; } } }
Maintain the same structure and functionality when rewriting this code in C++.
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc} proc toRREF {m} { set lead 0 lassign [size $m] rows cols for {set r 0} {$r < $rows} {incr r} { if {$cols <= $lead} { break } set i $r while {[lindex $m $i $lead] == 0} { incr i if {$rows == $i} { set i $r incr lead if {$cols == $lead} { return $m } } } foreach idx [list $i $r] row [list [lindex $m $r] [lindex $m $i]] { lset m $idx $row } set val [lindex $m $r $lead] for {set j 0} {$j < $cols} {incr j} { lset m $r $j [/ [double [lindex $m $r $j]] $val] } for {set i 0} {$i < $rows} {incr i} { if {$i != $r} { set val [lindex $m $i $lead] for {set j 0} {$j < $cols} {incr j} { lset m $i $j [- [lindex $m $i $j] [* $val [lindex $m $r $j]]] } } } incr lead } return $m } set m {{1 2 -1 -4} {2 3 -1 -11} {-2 0 -3 22}} print_matrix $m print_matrix [toRREF $m]
#include <algorithm> #include <cstddef> #include <cassert> template<typename MatrixType> struct matrix_traits { typedef typename MatrixType::index_type index_type; typedef typename MatrixType::value_type value_type; static index_type min_row(MatrixType const& A) { return A.min_row(); } static index_type max_row(MatrixType const& A) { return A.max_row(); } static index_type min_column(MatrixType const& A) { return A.min_column(); } static index_type max_column(MatrixType const& A) { return A.max_column(); } static value_type& element(MatrixType& A, index_type i, index_type k) { return A(i,k); } static value_type element(MatrixType const& A, index_type i, index_type k) { return A(i,k); } }; template<typename T, std::size_t rows, std::size_t columns> struct matrix_traits<T[rows][columns]> { typedef std::size_t index_type; typedef T value_type; static index_type min_row(T const (&)[rows][columns]) { return 0; } static index_type max_row(T const (&)[rows][columns]) { return rows-1; } static index_type min_column(T const (&)[rows][columns]) { return 0; } static index_type max_column(T const (&)[rows][columns]) { return columns-1; } static value_type& element(T (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } static value_type element(T const (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } }; template<typename MatrixType> void swap_rows(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) std::swap(mt.element(A, i, col), mt.element(A, k, col)); } template<typename MatrixType> void divide_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(v != 0); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) /= v; } template<typename MatrixType> void add_multiple_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) += v * mt.element(A, k, col); } template<typename MatrixType> void to_reduced_row_echelon_form(MatrixType& A) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; index_type lead = mt.min_row(A); for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row) { if (lead > mt.max_column(A)) return; index_type i = row; while (mt.element(A, i, lead) == 0) { ++i; if (i > mt.max_row(A)) { i = row; ++lead; if (lead > mt.max_column(A)) return; } } swap_rows(A, i, row); divide_row(A, row, mt.element(A, row, lead)); for (i = mt.min_row(A); i <= mt.max_row(A); ++i) { if (i != row) add_multiple_row(A, i, row, -mt.element(A, i, lead)); } } } #include <iostream> int main() { double M[3][4] = { { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; to_reduced_row_echelon_form(M); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) std::cout << M[i][j] << '\t'; std::cout << "\n"; } return EXIT_SUCCESS; }
Ensure the translated Java code behaves exactly like the original Tcl snippet.
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc} proc toRREF {m} { set lead 0 lassign [size $m] rows cols for {set r 0} {$r < $rows} {incr r} { if {$cols <= $lead} { break } set i $r while {[lindex $m $i $lead] == 0} { incr i if {$rows == $i} { set i $r incr lead if {$cols == $lead} { return $m } } } foreach idx [list $i $r] row [list [lindex $m $r] [lindex $m $i]] { lset m $idx $row } set val [lindex $m $r $lead] for {set j 0} {$j < $cols} {incr j} { lset m $r $j [/ [double [lindex $m $r $j]] $val] } for {set i 0} {$i < $rows} {incr i} { if {$i != $r} { set val [lindex $m $i $lead] for {set j 0} {$j < $cols} {incr j} { lset m $i $j [- [lindex $m $i $j] [* $val [lindex $m $r $j]]] } } } incr lead } return $m } set m {{1 2 -1 -4} {2 3 -1 -11} {-2 0 -3 22}} print_matrix $m print_matrix [toRREF $m]
import java.util.*; import java.lang.Math; import org.apache.commons.math.fraction.Fraction; import org.apache.commons.math.fraction.FractionConversionException; class Matrix { LinkedList<LinkedList<Fraction>> matrix; int numRows; int numCols; static class Coordinate { int row; int col; Coordinate(int r, int c) { row = r; col = c; } public String toString() { return "(" + row + ", " + col + ")"; } } Matrix(double [][] m) { numRows = m.length; numCols = m[0].length; matrix = new LinkedList<LinkedList<Fraction>>(); for (int i = 0; i < numRows; i++) { matrix.add(new LinkedList<Fraction>()); for (int j = 0; j < numCols; j++) { try { matrix.get(i).add(new Fraction(m[i][j])); } catch (FractionConversionException e) { System.err.println("Fraction could not be converted from double by apache commons . . ."); } } } } public void Interchange(Coordinate a, Coordinate b) { LinkedList<Fraction> temp = matrix.get(a.row); matrix.set(a.row, matrix.get(b.row)); matrix.set(b.row, temp); int t = a.row; a.row = b.row; b.row = t; } public void Scale(Coordinate x, Fraction d) { LinkedList<Fraction> row = matrix.get(x.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).multiply(d)); } } public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) { LinkedList<Fraction> row = matrix.get(to.row); LinkedList<Fraction> rowMultiplied = matrix.get(from.row); for (int i = 0; i < numCols; i++) { row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar)))); } } public void RREF() { Coordinate pivot = new Coordinate(0,0); int submatrix = 0; for (int x = 0; x < numCols; x++) { pivot = new Coordinate(pivot.row, x); for (int i = x; i < numCols; i++) { if (isColumnZeroes(pivot) == false) { break; } else { pivot.col = i; } } pivot = findPivot(pivot); if (getCoordinate(pivot).doubleValue() == 0.0) { pivot.row++; continue; } if (pivot.row != submatrix) { Interchange(new Coordinate(submatrix, pivot.col), pivot); } if (getCoordinate(pivot).doubleValue() != 1) { Fraction scalar = getCoordinate(pivot).reciprocal(); Scale(pivot, scalar); } for (int i = pivot.row; i < numRows; i++) { if (i == pivot.row) { continue; } Coordinate belowPivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(belowPivot, pivot, complement); } for (int i = pivot.row; i >= 0; i--) { if (i == pivot.row) { if (getCoordinate(pivot).doubleValue() != 1.0) { Scale(pivot, getCoordinate(pivot).reciprocal()); } continue; } if (i == pivot.row) { continue; } Coordinate abovePivot = new Coordinate(i, pivot.col); Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot))); MultiplyAndAdd(abovePivot, pivot, complement); } if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) { break; } submatrix++; pivot.row++; } } public boolean isColumnZeroes(Coordinate a) { for (int i = 0; i < numRows; i++) { if (matrix.get(i).get(a.col).doubleValue() != 0.0) { return false; } } return true; } public boolean isRowZeroes(Coordinate a) { for (int i = 0; i < numCols; i++) { if (matrix.get(a.row).get(i).doubleValue() != 0.0) { return false; } } return true; } public Coordinate findPivot(Coordinate a) { int first_row = a.row; Coordinate pivot = new Coordinate(a.row, a.col); Coordinate current = new Coordinate(a.row, a.col); for (int i = a.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() == 1.0) { Interchange(current, a); } } current.row = a.row; for (int i = current.row; i < (numRows - first_row); i++) { current.row = i; if (getCoordinate(current).doubleValue() != 0) { pivot.row = i; break; } } return pivot; } public Fraction getCoordinate(Coordinate a) { return matrix.get(a.row).get(a.col); } public String toString() { return matrix.toString().replace("], ", "]\n"); } public static void main (String[] args) { double[][] matrix_1 = { {1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22} }; Matrix x = new Matrix(matrix_1); System.out.println("before\n" + x.toString() + "\n"); x.RREF(); System.out.println("after\n" + x.toString() + "\n"); double matrix_2 [][] = { {2, 0, -1, 0, 0}, {1, 0, 0, -1, 0}, {3, 0, 0, -2, -1}, {0, 1, 0, 0, -2}, {0, 1, -1, 0, 0} }; Matrix y = new Matrix(matrix_2); System.out.println("before\n" + y.toString() + "\n"); y.RREF(); System.out.println("after\n" + y.toString() + "\n"); double matrix_3 [][] = { {1, 2, 3, 4, 3, 1}, {2, 4, 6, 2, 6, 2}, {3, 6, 18, 9, 9, -6}, {4, 8, 12, 10, 12, 4}, {5, 10, 24, 11, 15, -4} }; Matrix z = new Matrix(matrix_3); System.out.println("before\n" + z.toString() + "\n"); z.RREF(); System.out.println("after\n" + z.toString() + "\n"); double matrix_4 [][] = { {0, 1}, {1, 2}, {0,5} }; Matrix a = new Matrix(matrix_4); System.out.println("before\n" + a.toString() + "\n"); a.RREF(); System.out.println("after\n" + a.toString() + "\n"); } }
Translate this program into Python but keep the logic exactly as in Tcl.
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc} proc toRREF {m} { set lead 0 lassign [size $m] rows cols for {set r 0} {$r < $rows} {incr r} { if {$cols <= $lead} { break } set i $r while {[lindex $m $i $lead] == 0} { incr i if {$rows == $i} { set i $r incr lead if {$cols == $lead} { return $m } } } foreach idx [list $i $r] row [list [lindex $m $r] [lindex $m $i]] { lset m $idx $row } set val [lindex $m $r $lead] for {set j 0} {$j < $cols} {incr j} { lset m $r $j [/ [double [lindex $m $r $j]] $val] } for {set i 0} {$i < $rows} {incr i} { if {$i != $r} { set val [lindex $m $i $lead] for {set j 0} {$j < $cols} {incr j} { lset m $i $j [- [lindex $m $i $j] [* $val [lindex $m $r $j]]] } } } incr lead } return $m } set m {{1 2 -1 -4} {2 3 -1 -11} {-2 0 -3 22}} print_matrix $m print_matrix [toRREF $m]
def ToReducedRowEchelonForm( M): if not M: return lead = 0 rowCount = len(M) columnCount = len(M[0]) for r in range(rowCount): if lead >= columnCount: return i = r while M[i][lead] == 0: i += 1 if i == rowCount: i = r lead += 1 if columnCount == lead: return M[i],M[r] = M[r],M[i] lv = M[r][lead] M[r] = [ mrx / float(lv) for mrx in M[r]] for i in range(rowCount): if i != r: lv = M[i][lead] M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])] lead += 1 mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22],] ToReducedRowEchelonForm( mtx ) for rw in mtx: print ', '.join( (str(rv) for rv in rw) )
Convert the following code from Tcl to VB, ensuring the logic remains intact.
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc} proc toRREF {m} { set lead 0 lassign [size $m] rows cols for {set r 0} {$r < $rows} {incr r} { if {$cols <= $lead} { break } set i $r while {[lindex $m $i $lead] == 0} { incr i if {$rows == $i} { set i $r incr lead if {$cols == $lead} { return $m } } } foreach idx [list $i $r] row [list [lindex $m $r] [lindex $m $i]] { lset m $idx $row } set val [lindex $m $r $lead] for {set j 0} {$j < $cols} {incr j} { lset m $r $j [/ [double [lindex $m $r $j]] $val] } for {set i 0} {$i < $rows} {incr i} { if {$i != $r} { set val [lindex $m $i $lead] for {set j 0} {$j < $cols} {incr j} { lset m $i $j [- [lindex $m $i $j] [* $val [lindex $m $r $j]]] } } } incr lead } return $m } set m {{1 2 -1 -4} {2 3 -1 -11} {-2 0 -3 22}} print_matrix $m print_matrix [toRREF $m]
Private Function ToReducedRowEchelonForm(M As Variant) As Variant Dim lead As Integer: lead = 0 Dim rowCount As Integer: rowCount = UBound(M) Dim columnCount As Integer: columnCount = UBound(M(0)) Dim i As Integer For r = 0 To rowCount If lead >= columnCount Then Exit For End If i = r Do While M(i)(lead) = 0 i = i + 1 If i = rowCount Then i = r lead = lead + 1 If lead = columnCount Then Exit For End If End If Loop Dim tmp As Variant tmp = M(r) M(r) = M(i) M(i) = tmp If M(r)(lead) <> 0 Then div = M(r)(lead) For t = LBound(M(r)) To UBound(M(r)) M(r)(t) = M(r)(t) / div Next t End If For j = 0 To rowCount If j <> r Then subt = M(j)(lead) For t = LBound(M(j)) To UBound(M(j)) M(j)(t) = M(j)(t) - subt * M(r)(t) Next t End If Next j lead = lead + 1 Next r ToReducedRowEchelonForm = M End Function Public Sub main() r = ToReducedRowEchelonForm(Array( _ Array(1, 2, -1, -4), _ Array(2, 3, -1, -11), _ Array(-2, 0, -3, 22))) For i = LBound(r) To UBound(r) Debug.Print Join(r(i), vbTab) Next i End Sub
Change the programming language of this snippet from Tcl to Go without modifying what it does.
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc} proc toRREF {m} { set lead 0 lassign [size $m] rows cols for {set r 0} {$r < $rows} {incr r} { if {$cols <= $lead} { break } set i $r while {[lindex $m $i $lead] == 0} { incr i if {$rows == $i} { set i $r incr lead if {$cols == $lead} { return $m } } } foreach idx [list $i $r] row [list [lindex $m $r] [lindex $m $i]] { lset m $idx $row } set val [lindex $m $r $lead] for {set j 0} {$j < $cols} {incr j} { lset m $r $j [/ [double [lindex $m $r $j]] $val] } for {set i 0} {$i < $rows} {incr i} { if {$i != $r} { set val [lindex $m $i $lead] for {set j 0} {$j < $cols} {incr j} { lset m $i $j [- [lindex $m $i $j] [* $val [lindex $m $r $j]]] } } } incr lead } return $m } set m {{1 2 -1 -4} {2 3 -1 -11} {-2 0 -3 22}} print_matrix $m print_matrix [toRREF $m]
package main import "fmt" type matrix [][]float64 func (m matrix) print() { for _, r := range m { fmt.Println(r) } fmt.Println("") } func main() { m := matrix{ { 1, 2, -1, -4}, { 2, 3, -1, -11}, {-2, 0, -3, 22}, } m.print() rref(m) m.print() } func rref(m matrix) { lead := 0 rowCount := len(m) columnCount := len(m[0]) for r := 0; r < rowCount; r++ { if lead >= columnCount { return } i := r for m[i][lead] == 0 { i++ if rowCount == i { i = r lead++ if columnCount == lead { return } } } m[i], m[r] = m[r], m[i] f := 1 / m[r][lead] for j, _ := range m[r] { m[r][j] *= f } for i = 0; i < rowCount; i++ { if i != r { f = m[i][lead] for j, e := range m[r] { m[i][j] -= e * f } } } lead++ } }
Ensure the translated PHP code behaves exactly like the original Rust snippet.
fn main() { let mut matrix_to_reduce: Vec<Vec<f64>> = vec![vec![1.0, 2.0 , -1.0, -4.0], vec![2.0, 3.0, -1.0, -11.0], vec![-2.0, 0.0, -3.0, 22.0]]; let mut r_mat_to_red = &mut matrix_to_reduce; let rr_mat_to_red = &mut r_mat_to_red; println!("Matrix to reduce:\n{:?}", rr_mat_to_red); let reduced_matrix = reduced_row_echelon_form(rr_mat_to_red); println!("Reduced matrix:\n{:?}", reduced_matrix); } fn reduced_row_echelon_form(matrix: &mut Vec<Vec<f64>>) -> Vec<Vec<f64>> { let mut matrix_out: Vec<Vec<f64>> = matrix.to_vec(); let mut pivot = 0; let row_count = matrix_out.len(); let column_count = matrix_out[0].len(); 'outer: for r in 0..row_count { if column_count <= pivot { break; } let mut i = r; while matrix_out[i][pivot] == 0.0 { i = i+1; if i == row_count { i = r; pivot = pivot + 1; if column_count == pivot { pivot = pivot - 1; break 'outer; } } } for j in 0..row_count { let temp = matrix_out[r][j]; matrix_out[r][j] = matrix_out[i][j]; matrix_out[i][j] = temp; } let divisor = matrix_out[r][pivot]; if divisor != 0.0 { for j in 0..column_count { matrix_out[r][j] = matrix_out[r][j] / divisor; } } for j in 0..row_count { if j != r { let hold = matrix_out[j][pivot]; for k in 0..column_count { matrix_out[j][k] = matrix_out[j][k] - ( hold * matrix_out[r][k]); } } } pivot = pivot + 1; } matrix_out }
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Transform the following Ada implementation into PHP, maintaining the same output and logic.
generic type Element_Type is private; Zero : Element_Type; with function "-" (Left, Right : in Element_Type) return Element_Type is <>; with function "*" (Left, Right : in Element_Type) return Element_Type is <>; with function "/" (Left, Right : in Element_Type) return Element_Type is <>; package Matrices is type Matrix is array (Positive range <>, Positive range <>) of Element_Type; function Reduced_Row_Echelon_form (Source : Matrix) return Matrix; end Matrices;
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Generate an equivalent PHP version of this AutoHotKey code.
ToReducedRowEchelonForm(M){ rowCount := M.Count() columnCount := M.1.Count() r := lead := 1 while (r <= rowCount) { if (columnCount < lead) return M i := r while (M[i, lead] = 0) { i++ if (rowCount+1 = i) { i := r, lead++ if (columnCount+1 = lead) return M } } if (i<>r) for col, v in M[i] tempVal := M[i, col], M[i, col] := M[r, col], M[r, col] := tempVal num := M[r, lead] if (M[r, lead] <> 0) for col, val in M[r] M[r, col] /= num i := 2 while (i <= rowCount) { num := M[i, lead] if (i <> r) for col, val in M[i] M[i, col] -= num * M[r, col] i++ } lead++, r++ } return M }
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Change the following BBC_Basic code into PHP without altering its purpose.
DIM matrix(2,3) matrix() = 1, 2, -1, -4, \ \ 2, 3, -1, -11, \ \ -2, 0, -3, 22 PROCrref(matrix()) FOR row% = 0 TO 2 FOR col% = 0 TO 3 PRINT matrix(row%,col%); NEXT PRINT NEXT row% END DEF PROCrref(m()) LOCAL lead%, nrows%, ncols%, i%, j%, r%, n nrows% = DIM(m(),1)+1 ncols% = DIM(m(),2)+1 FOR r% = 0 TO nrows%-1 IF lead% >= ncols% EXIT FOR i% = r% WHILE m(i%,lead%) = 0 i% += 1 IF i% = nrows% THEN i% = r% lead% += 1 IF lead% = ncols% EXIT FOR ENDIF ENDWHILE FOR j% = 0 TO ncols%-1 : SWAP m(i%,j%),m(r%,j%) : NEXT n = m(r%,lead%) IF n <> 0 FOR j% = 0 TO ncols%-1 : m(r%,j%) /= n : NEXT FOR i% = 0 TO nrows%-1 IF i% <> r% THEN n = m(i%,lead%) FOR j% = 0 TO ncols%-1 m(i%,j%) -= m(r%,j%) * n NEXT ENDIF NEXT lead% += 1 NEXT r% ENDPROC
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Change the programming language of this snippet from Common_Lisp to PHP without modifying what it does.
(defun convert-to-row-echelon-form (matrix) (let* ((dimensions (array-dimensions matrix)) (row-count (first dimensions)) (column-count (second dimensions)) (lead 0)) (labels ((find-pivot (start lead) (let ((i start)) (loop :while (zerop (aref matrix i lead)) :do (progn (incf i) (when (= i row-count) (setf i start) (incf lead) (when (= lead column-count) (return-from convert-to-row-echelon-form matrix)))) :finally (return (values i lead))))) (swap-rows (r1 r2) (loop :for c :upfrom 0 :below column-count :do (rotatef (aref matrix r1 c) (aref matrix r2 c)))) (divide-row (r value) (loop :for c :upfrom 0 :below column-count :do (setf (aref matrix r c) (/ (aref matrix r c) value))))) (loop :for r :upfrom 0 :below row-count :when (<= column-count lead) :do (return matrix) :do (multiple-value-bind (i nlead) (find-pivot r lead) (setf lead nlead) (swap-rows i r) (divide-row r (aref matrix r lead)) (loop :for i :upfrom 0 :below row-count :when (/= i r) :do (let ((scale (aref matrix i lead))) (loop :for c :upfrom 0 :below column-count :do (decf (aref matrix i c) (* scale (aref matrix r c)))))) (incf lead)) :finally (return matrix)))))
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Write the same algorithm in PHP as shown in this D implementation.
import std.stdio, std.algorithm, std.array, std.conv; void toReducedRowEchelonForm(T)(T[][] M) pure nothrow @nogc { if (M.empty) return; immutable nrows = M.length; immutable ncols = M[0].length; size_t lead; foreach (immutable r; 0 .. nrows) { if (ncols <= lead) return; { size_t i = r; while (M[i][lead] == 0) { i++; if (nrows == i) { i = r; lead++; if (ncols == lead) return; } } swap(M[i], M[r]); } M[r][] /= M[r][lead]; foreach (j, ref mj; M) if (j != r) mj[] -= M[r][] * mj[lead]; lead++; } } void main() { auto A = [[ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22]]; A.toReducedRowEchelonForm; writefln("%(%(%2d %)\n%)", A); }
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Port the provided Factor code into PHP while preserving the original functionality.
USE: math.matrices.elimination { { 1 2 -1 -4 } { 2 3 -1 -11 } { -2 0 -3 22 } } solution .
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Keep all operations the same but rewrite the snippet in PHP.
module Rref implicit none contains subroutine to_rref(matrix) real, dimension(:,:), intent(inout) :: matrix integer :: pivot, norow, nocolumn integer :: r, i real, dimension(:), allocatable :: trow pivot = 1 norow = size(matrix, 1) nocolumn = size(matrix, 2) allocate(trow(nocolumn)) do r = 1, norow if ( nocolumn <= pivot ) exit i = r do while ( matrix(i, pivot) == 0 ) i = i + 1 if ( norow == i ) then i = r pivot = pivot + 1 if ( nocolumn == pivot ) return end if end do trow = matrix(i, :) matrix(i, :) = matrix(r, :) matrix(r, :) = trow matrix(r, :) = matrix(r, :) / matrix(r, pivot) do i = 1, norow if ( i /= r ) matrix(i, :) = matrix(i, :) - matrix(r, :) * matrix(i, pivot) end do pivot = pivot + 1 end do deallocate(trow) end subroutine to_rref end module Rref
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Please provide an equivalent version of this Groovy code in PHP.
enum Pivoting { NONE({ i, it -> 1 }), PARTIAL({ i, it -> - (it[i].abs()) }), SCALED({ i, it -> - it[i].abs()/(it.inject(0) { sum, elt -> sum + elt.abs() } ) }); public final Closure comparer private Pivoting(Closure c) { comparer = c } } def isReducibleMatrix = { matrix -> def m = matrix.size() m > 1 && matrix[0].size() > m && matrix[1..<m].every { row -> row.size() == matrix[0].size() } } def reducedRowEchelonForm = { matrix, Pivoting pivoting = Pivoting.NONE -> assert isReducibleMatrix(matrix) def m = matrix.size() def n = matrix[0].size() (0..<m).each { i -> matrix[i..<m].sort(pivoting.comparer.curry(i)) matrix[i][i..<n] = matrix[i][i..<n].collect { it/matrix[i][i] } ((0..<i) + ((i+1)..<m)).each { k -> (i..<n).reverse().each { j -> matrix[k][j] -= matrix[i][j]*matrix[k][i] } } } matrix }
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Write the same code in PHP as shown below in Haskell.
import Data.List (find) rref :: Fractional a => [[a]] -> [[a]] rref m = f m 0 [0 .. rows - 1] where rows = length m cols = length $ head m f m _ [] = m f m lead (r : rs) | indices == Nothing = m | otherwise = f m' (lead' + 1) rs where indices = find p l p (col, row) = m !! row !! col /= 0 l = [(col, row) | col <- [lead .. cols - 1], row <- [r .. rows - 1]] Just (lead', i) = indices newRow = map (/ m !! i !! lead') $ m !! i m' = zipWith g [0..] $ replace r newRow $ replace i (m !! r) m g n row | n == r = row | otherwise = zipWith h newRow row where h = subtract . (* row !! lead') replace :: Int -> a -> [a] -> [a] replace n e l = a ++ e : b where (a, _ : b) = splitAt n l
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Rewrite the snippet below in PHP so it works the same as the original J code.
require 'math/misc/linear' ]A=: 1 2 _1 _4 , 2 3 _1 _11 ,: _2 0 _3 22 1 2 _1 _4 2 3 _1 _11 _2 0 _3 22 gauss_jordan A 1 0 0 _8 0 1 0 1 0 0 1 _2
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Please provide an equivalent version of this Lua code in PHP.
function ToReducedRowEchelonForm ( M ) local lead = 1 local n_rows, n_cols = #M, #M[1] for r = 1, n_rows do if n_cols <= lead then break end local i = r while M[i][lead] == 0 do i = i + 1 if n_rows == i then i = r lead = lead + 1 if n_cols == lead then break end end end M[i], M[r] = M[r], M[i] local m = M[r][lead] for k = 1, n_cols do M[r][k] = M[r][k] / m end for i = 1, n_rows do if i ~= r then local m = M[i][lead] for k = 1, n_cols do M[i][k] = M[i][k] - m * M[r][k] end end end lead = lead + 1 end end M = { { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } } res = ToReducedRowEchelonForm( M ) for i = 1, #M do for j = 1, #M[1] do io.write( M[i][j], " " ) end io.write( "\n" ) end
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Port the following code from Mathematica to PHP with equivalent syntax and logic.
RowReduce[{{1, 2, -1, -4}, {2, 3, -1, -11}, {-2, 0, -3, 22}}]
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Change the following MATLAB code into PHP without altering its purpose.
rref([1, 2, -1, -4; 2, 3, -1, -11; -2, 0, -3, 22])
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Write the same code in PHP as shown below in Nim.
import rationals, strutils type Fraction = Rational[int] const Zero: Fraction = 0 // 1 type Matrix[M, N: static Positive] = array[M, array[N, Fraction]] func toMatrix[M, N: static Positive](a: array[M, array[N, int]]): Matrix[M, N] = for i in 0..<M: for j in 0..<N: result[i][j] = a[i][j] // 1 func transformToRref(mat: var Matrix) = var lead = 0 for r in 0..<mat.M: if lead >= mat.N: return var i = r while mat[i][lead] == Zero: inc i if i == mat.M: i = r inc lead if lead == mat.N: return swap mat[i], mat[r] if (let d = mat[r][lead]; d) != Zero: for item in mat[r].mitems: item /= d for i in 0..<mat.M: if i != r: let m = mat[i][lead] for c in 0..<mat.N: mat[i][c] -= mat[r][c] * m inc lead proc `$`(mat: Matrix): string = for row in mat: var line = "" for val in row: line.addSep(" ", 0) line.add val.toFloat.formatFloat(ffDecimal, 2).align(7) echo line template runTest(mat: Matrix) = echo "Original matrix:" echo mat echo "Reduced row echelon form:" mat.transformToRref() echo mat echo "" var m1 = [[ 1, 2, -1, -4], [ 2, 3, -1, -11], [-2, 0, -3, 22]].toMatrix() var m2 = [[2, 0, -1, 0, 0], [1, 0, 0, -1, 0], [3, 0, 0, -2, -1], [0, 1, 0, 0, -2], [0, 1, -1, 0, 0]].toMatrix() var m3 = [[1, 2, 3, 4, 3, 1], [2, 4, 6, 2, 6, 2], [3, 6, 18, 9, 9, -6], [4, 8, 12, 10, 12, 4], [5, 10, 24, 11, 15, -4]].toMatrix() var m4 = [[0, 1], [1, 2], [0, 5]].toMatrix() runTest(m1) runTest(m2) runTest(m3) runTest(m4)
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Rewrite this program in PHP while keeping its functionality equivalent to the OCaml version.
let swap_rows m i j = let tmp = m.(i) in m.(i) <- m.(j); m.(j) <- tmp; ;; let rref m = try let lead = ref 0 and rows = Array.length m and cols = Array.length m.(0) in for r = 0 to pred rows do if cols <= !lead then raise Exit; let i = ref r in while m.(!i).(!lead) = 0 do incr i; if rows = !i then begin i := r; incr lead; if cols = !lead then raise Exit; end done; swap_rows m !i r; let lv = m.(r).(!lead) in m.(r) <- Array.map (fun v -> v / lv) m.(r); for i = 0 to pred rows do if i <> r then let lv = m.(i).(!lead) in m.(i) <- Array.mapi (fun i iv -> iv - lv * m.(r).(i)) m.(i); done; incr lead; done with Exit -> () ;; let () = let m = [| [| 1; 2; -1; -4 |]; [| 2; 3; -1; -11 |]; [| -2; 0; -3; 22 |]; |] in rref m; Array.iter (fun row -> Array.iter (fun v -> Printf.printf " %d" v ) row; print_newline() ) m
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Generate a PHP translation of this Perl snippet without changing its computational steps.
sub rref {our @m; local *m = shift; @m or return; my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]})); foreach my $r (0 .. $rows - 1) {$lead < $cols or return; my $i = $r; until ($m[$i][$lead]) {++$i == $rows or next; $i = $r; ++$lead == $cols and return;} @m[$i, $r] = @m[$r, $i]; my $lv = $m[$r][$lead]; $_ /= $lv foreach @{ $m[$r] }; my @mr = @{ $m[$r] }; foreach my $i (0 .. $rows - 1) {$i == $r and next; ($lv, my $n) = ($m[$i][$lead], -1); $_ -= $lv * $mr[++$n] foreach @{ $m[$i] };} ++$lead;}} sub display { join("\n" => map join(" " => map(sprintf("%4d", $_), @$_)), @{+shift})."\n" } @m = ( [ 1, 2, -1, -4 ], [ 2, 3, -1, -11 ], [ -2, 0, -3, 22 ] ); rref(\@m); print display(\@m);
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Transform the following Racket implementation into PHP, maintaining the same output and logic.
#lang racket (require math) (define (reduced-echelon M) (matrix-row-echelon M #t #t)) (reduced-echelon (matrix [[1 2 -1 -4] [2 3 -1 -11] [-2 0 -3 22]]))
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Keep all operations the same but rewrite the snippet in PHP.
cols= 0; w= 0; @. =0 mat.=; mat.1= ' 1 2 -1 -4 ' mat.2= ' 2 3 -1 -11 ' mat.3= ' -2 0 -3 22 ' do r=1 until mat.r==''; _=mat.r do c=1 until _=''; parse var _ @.r.c _ w= max(w, length(@.r.c) + 1) end cols= max(cols, c) end rows= r-1 call showMat 'original matrix' != 1 do r=1 for rows while cols>! j= r do while @.j.!==0; j= j + 1 if j==rows then do; j= r; != ! + 1; if cols==! then leave r; end end do _=1 for cols while j\==r; parse value @.r._ @.j._ with @.j._ @._._ end ?= @.r.! do d=1 for cols while ?\=1; @.r.d= @.r.d / ? end do k=1 for rows; ?= @.k.! if k==r | ?=0 then iterate do s=1 for cols; @.k.s= @.k.s - ? * @.r.s end end != !+1 end call showMat 'matrix RREF' exit showMat: parse arg title; say; say center(title, 3 + (cols+1) * w, '─'); say do r=1 for rows; _= do c=1 for cols if @.r.c=='' then do; say "***error*** matrix element isn't defined:" say 'row' r", column" c'.'; exit 13 end _= _ right(@.r.c, w) end say _ end
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Preserve the algorithm and functionality while converting the code from Ruby to PHP.
def reduced_row_echelon_form(ary) lead = 0 rows = ary.size cols = ary[0].size rary = convert_to(ary, :to_r) catch :done do rows.times do |r| throw :done if cols <= lead i = r while rary[i][lead] == 0 i += 1 if rows == i i = r lead += 1 throw :done if cols == lead end end rary[i], rary[r] = rary[r], rary[i] v = rary[r][lead] rary[r].collect! {|x| x / v} rows.times do |i| next if i == r v = rary[i][lead] rary[i].each_index {|j| rary[i][j] -= v * rary[r][j]} end lead += 1 end end rary end def convert_to(ary, type) ary.each_with_object([]) do |row, new| new << row.collect {|elem| elem.send(type)} end end class Rational alias _to_s to_s def to_s denominator==1 ? numerator.to_s : _to_s end end def print_matrix(m) max = m[0].collect {-1} m.each {|row| row.each_index {|i| max[i] = [max[i], row[i].to_s.length].max}} m.each {|row| row.each_index {|i| print "% end mtx = [ [ 1, 2, -1, -4], [ 2, 3, -1,-11], [-2, 0, -3, 22] ] print_matrix reduced_row_echelon_form(mtx) puts mtx = [ [ 1, 2, 3, 7], [-4, 7,-2, 7], [ 3, 3, 0, 7] ] reduced = reduced_row_echelon_form(mtx) print_matrix reduced print_matrix convert_to(reduced, :to_f)
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Convert the following code from Scala to PHP, ensuring the logic remains intact.
typealias Matrix = Array<DoubleArray> fun Matrix.toReducedRowEchelonForm() { var lead = 0 val rowCount = this.size val colCount = this[0].size for (r in 0 until rowCount) { if (colCount <= lead) return var i = r while (this[i][lead] == 0.0) { i++ if (rowCount == i) { i = r lead++ if (colCount == lead) return } } val temp = this[i] this[i] = this[r] this[r] = temp if (this[r][lead] != 0.0) { val div = this[r][lead] for (j in 0 until colCount) this[r][j] /= div } for (k in 0 until rowCount) { if (k != r) { val mult = this[k][lead] for (j in 0 until colCount) this[k][j] -= this[r][j] * mult } } lead++ } } fun Matrix.printf(title: String) { println(title) val rowCount = this.size val colCount = this[0].size for (r in 0 until rowCount) { for (c in 0 until colCount) { if (this[r][c] == -0.0) this[r][c] = 0.0 print("${"% 6.2f".format(this[r][c])} ") } println() } println() } fun main(args: Array<String>) { val matrices = listOf( arrayOf( doubleArrayOf( 1.0, 2.0, -1.0, -4.0), doubleArrayOf( 2.0, 3.0, -1.0, -11.0), doubleArrayOf(-2.0, 0.0, -3.0, 22.0) ), arrayOf( doubleArrayOf(1.0, 2.0, 3.0, 4.0, 3.0, 1.0), doubleArrayOf(2.0, 4.0, 6.0, 2.0, 6.0, 2.0), doubleArrayOf(3.0, 6.0, 18.0, 9.0, 9.0, -6.0), doubleArrayOf(4.0, 8.0, 12.0, 10.0, 12.0, 4.0), doubleArrayOf(5.0, 10.0, 24.0, 11.0, 15.0, -4.0) ) ) for (m in matrices) { m.printf("Original matrix:") m.toReducedRowEchelonForm() m.printf("Reduced row echelon form:") } }
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Change the programming language of this snippet from Swift to PHP without modifying what it does.
var lead = 0 for r in 0..<rows { if (cols <= lead) { break } var i = r while (m[i][lead] == 0) { i += 1 if (i == rows) { i = r lead += 1 if (cols == lead) { lead -= 1 break } } } for j in 0..<cols { let temp = m[r][j] m[r][j] = m[i][j] m[i][j] = temp } let div = m[r][lead] if (div != 0) { for j in 0..<cols { m[r][j] /= div } } for j in 0..<rows { if (j != r) { let sub = m[j][lead] for k in 0..<cols { m[j][k] -= (sub * m[r][k]) } } } lead += 1 }
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>
Write a version of this Tcl function in PHP with identical behavior.
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc} proc toRREF {m} { set lead 0 lassign [size $m] rows cols for {set r 0} {$r < $rows} {incr r} { if {$cols <= $lead} { break } set i $r while {[lindex $m $i $lead] == 0} { incr i if {$rows == $i} { set i $r incr lead if {$cols == $lead} { return $m } } } foreach idx [list $i $r] row [list [lindex $m $r] [lindex $m $i]] { lset m $idx $row } set val [lindex $m $r $lead] for {set j 0} {$j < $cols} {incr j} { lset m $r $j [/ [double [lindex $m $r $j]] $val] } for {set i 0} {$i < $rows} {incr i} { if {$i != $r} { set val [lindex $m $i $lead] for {set j 0} {$j < $cols} {incr j} { lset m $i $j [- [lindex $m $i $j] [* $val [lindex $m $r $j]]] } } } incr lead } return $m } set m {{1 2 -1 -4} {2 3 -1 -11} {-2 0 -3 22}} print_matrix $m print_matrix [toRREF $m]
<?php function rref($matrix) { $lead = 0; $rowCount = count($matrix); if ($rowCount == 0) return $matrix; $columnCount = 0; if (isset($matrix[0])) { $columnCount = count($matrix[0]); } for ($r = 0; $r < $rowCount; $r++) { if ($lead >= $columnCount) break; { $i = $r; while ($matrix[$i][$lead] == 0) { $i++; if ($i == $rowCount) { $i = $r; $lead++; if ($lead == $columnCount) return $matrix; } } $temp = $matrix[$r]; $matrix[$r] = $matrix[$i]; $matrix[$i] = $temp; } { $lv = $matrix[$r][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$r][$j] = $matrix[$r][$j] / $lv; } } for ($i = 0; $i < $rowCount; $i++) { if ($i != $r) { $lv = $matrix[$i][$lead]; for ($j = 0; $j < $columnCount; $j++) { $matrix[$i][$j] -= $lv * $matrix[$r][$j]; } } } $lead++; } return $matrix; } ?>