LU decomposition: Difference between revisions

Content deleted Content added
→‎Tcl: Added implementation
m →‎{{header|Tcl}}: Smarten up
Line 393:
=={{header|Tcl}}==
<lang tcl>package require Tcl 8.5
 
namespace eval matrix {
namespace path {::tcl::mathfunc ::tcl::mathop}
 
proc I {order} {
# Construct an identity matrix of the given size
proc Iidentity {order} {
set m [lrepeat $order [lrepeat $order 0]]
for {set i 0} {$i < $order} {incr i} {
Line 403 ⟶ 404:
return $m
}
 
# Produce the pivot matrix for a given matrix
proc pivotize {matrix} {
set n [llength $matrix]
set p [Iidentity $n]
for {set j 0} {$j < $n} {incr j} {
set max [lindex $matrix $j $j]
Line 416 ⟶ 419:
}
if {$j != $row} {
# Row swap inlined; too trivial to have separate procedure
set tmp [lindex $p $j]
lset p $j [lindex $p $row]
Line 424 ⟶ 428:
}
 
# DecomposesDecompose a square matrix A by PA=LU and returnsreturn L, U and P
proc luDecompose {A} {
set n [llength $A]
Line 455 ⟶ 459:
return $s
}
}</lang>
 
Support code:
<lang tcl># Code adapted from Matrix_multiplication and Matrix_transposition tasks
foreachnamespace roweval $matrix {
# Get the size of a matrix; assumes that all rows are the same length, which
# is a basic well-formed-ness condition...
proc size {m} {
set rows [llength $m]
Line 462 ⟶ 470:
return [list $rows $cols]
}
 
# Matrix multiplication implementation
proc multiply {a b} {
lassign [size $a] a_rows a_cols
Line 477 ⟶ 487:
}
 
# Pretty printer for matrices
proc print {matrix {fmt "%sg"}} {
set max [Widest $matrix $fmt]
lassign [size $matrix] rows cols
foreach val $row width $maxmatrix {
foreach val $row width $max {
puts -nonewline [format "%*s " $width [format $fmt $val]]
}
puts ""
}
}
proc Widest {m fmt} {
lassign [size $m] rows cols
Line 488 ⟶ 509:
return $max
}
}</lang>
proc print {matrix {fmt "%s"}} {
Demonstrating:
set max [Widest $matrix $fmt]
<lang tcl># This does the decomposition and prints it out nicely
lassign [size $matrix] rows cols
foreach row $matrix {
foreach val $row width $max {
puts -nonewline [format "%*s " $width [format $fmt $val]]
}
puts ""
}
}
}
 
# Demonstration helper
proc demo {A} {
lassign [matrix::luDecompose $A] L U P
Line 513 ⟶ 524:
puts "================================="
demo {{11 9 24 2} {1 5 2 6} {3 17 18 1} {2 5 7 1}}</lang>
Output:
<pre>
A: