Walsh matrix: Difference between revisions

(Add MATLAB implementation)
Line 790:
1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1
</pre>
 
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]]'''
{{Works with|jq}}
 
'''Works with gojq, the Go implementation of jq'''
 
'''Works with jaq, the Rust implementation of jq'''
<syntaxhighlight lang="jq">
## Generic matrix functions
 
# Create an m x n matrix
def matrix(m; n; init):
if m == 0 then []
elif m == 1 then [range(0;n) | init]
elif m > 0 then
matrix(1;n;init) as $row
| [range(0;m) | $row ]
else error("matrix\(m);_;_) invalid")
end;
 
# Input: a numeric array
def signChanges:
def s: if . > 0 then 1 elif . < 0 then -1 else 0 end;
. as $row
| reduce range(1;length) as $i (0;
if ($row[$i-1]|s) == -($row[$i]|s) then . + 1 else . end );
 
# Print a matrix of integers
# $width is the minimum width to use per cell
def mprint($width):
def max(s): reduce s as $x (null; if . == null or $x > . then $x else . end);
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
(max($width, (.[][] | tostring | length) + 1)) as $w
| . as $in
| range(0; length) as $i
| reduce range(0; .[$i]|length) as $j ("|"; . + ($in[$i][$j]|lpad($w)))
| . + " |" ;
</syntaxhighlight>
'''Walsh matrices'''
<syntaxhighlight lang="jq">
def walshMatrix:
. as $n
| { walsh: matrix($n; $n; 0) }
| .walsh[0][0] = 1
| .k = 1
| until (.k >= $n;
reduce range (0;.k) as $i (.;
reduce range (0;.k) as $j (.;
.walsh[$i][$j] as $wij
| .k as $k
| .walsh[$i+$k][$j] = $wij
| .walsh[$i][$j+$k] = $wij
| .walsh[$i+$k][$j+$k] = -$wij ))
| .k += .k )
| .walsh ;
 
## The tasks
def task1:
(2, 4, 5) as $order
| pow(2; $order)
| "Walsh matrix - order \($order) (\(.) x \(.)), natural order:",
(walshMatrix | mprint(2)),
"";
 
def task2:
(2, 4, 5) as $order
| pow(2; $order)
| "Walsh matrix - order \($order) (\(.) x \(.)), sequency order:",
(walshMatrix | sort_by( signChanges ) | mprint(2)),
"";
 
task1, task2
</syntaxhighlight>
{{output}}
Essentially as for [[#Wren|Wren]].
 
=={{header|Julia}}==
2,460

edits