Matlab "diff" in F# (subtract element by element) - matlab

There is a diff function in MATLAB, that computes difference between elements in vector (or matrix, but it is not the case now).
X = [1 1 2 3 5 8 13 21];
Y = diff(X)
Results in: 0 1 1 2 3 5 8
I came up with F# solution:
let x =[1;1;2;3;5;8;13;21]
let diff x = List.map2 (-) (x|> List.tail) (x|> List.take ((x|>List.length) - 1))
diff x
which results in same List, but I feel there should be a better way how to do difference in F#? Is there?

There's List.pairwise : 'T list -> ('T * 'T) list which gives you a list of consecutive pairs of items.
let x =[1;1;2;3;5;8;13;21]
let diff x =
x |> List.pairwise |> List.map (fun (x, y) -> y - x)

Working with sequences instead of lists there is a compact solution:
let diff x = Seq.map2 (-) (Seq.skip 1 x) x
This would not work with lists because List.map2 requires its arguments to have the same length. Seq.map2 does not have that requirement.
For your specific case you could do:
[1;1;2;3;5;8;13;21] |> diff |> List.ofSeq
if you want the result to be a list.

Related

Understanding the question in a Racket programming assignment

The question is :
A univariate polynomial of order n is given by the following equation.
Pn (x) = anxn + . . . + a2x2 + a1x + a0
Here, ai are the coefficients of the polynomial, and x is its unique variable. You might implement a procedure poly-3 for computing the polynomial of order 3 of x as follows.
(define (poly-3 x a0 a1 a2 a3)
(+ a0 (* a1 x) (* a2 x x) (* a3 x x x)))
In poly-3, the coefficients and the variable are bundled together as arguments; and you would have to specify the coefficients each time you want to compute the same polynomial with different values of x.
Instead, implement the procedure make-poly-3 that generates a procedure that computes the polynomial for an arbitrary x.
(define (make-poly-3 a0 a1 a2 a3)
...)
(define my-poly-3
(make-poly-3 1 2 3 4))
(my-poly-3 2)
Next, write a function sum-poly-3-range which will sum up the results for calling my-poly-3 for the values in a range:
(define (sum-poly-3-range from to)
...)
(sum-poly-3-range 1 50)
I am not understanding what I need to do (I am not asking for the programming solution, just steps).
My confusions:
Can't understand the workflow or say the steps I need to follow.
How to pass coefficients for the polynomial? Should I generate randomly or should I use the constant values of a0, a1,a2,a3?
When looping through the range should I use that value as x?
make-poly-3 is a procedure which takes four arguments, and which will return another procedure. The values of the four arguments it takes will be the values of the coefficients to the polynomial.
The procedure it returns will take a single argument, which will be the value of x at which the polynomial is to be evaluated.
So, for instance
(define linear (make-poly-3 0 1 0 0))
> (linear 2)
2
> (define squared (make-poly-3 0 0 1 0))
> (squared 2)
4
The sum-poly-3-range function uses whatever value my-poly-3 has (it 'uses my-poly-3 free' to use a bit of jargon), and evaluates it for every integer in a range which you give it, and works out the sum of the results.
So, as a simple example:
> (define my-poly-3 (make-poly-3 1 0 0 0))
> (sum-poly-3-range 1 50)
50
This is because (make-poly-3 1 0 0 0) returns a polynomial function which evaluates to 1 for all arguments (the constant term is the only non-zero term).
And
> (define my-poly-3 (make-poly-3 0 1 0 0))
> (sum-poly-3-range 1 50)
1275
because this polynomial just squares its argument.

What does y==x mean in MATLAB?

I came across some MATLAB code online and it was running just fine, but I couldn't understand the meaning of (y == x) where y is a column matrix and x is an integer.
someFunction(y == x);
Is it some kind of comparing or setting some value of y?
The instruction
y == x
checks which values in the array y (if any) are equals to the scalar x and returns a logical array of the size of y in which 1 is set in the location where the value of the element of y is equal to the value of x and 0 in the other case.
It ha to be assumed tha also the array y is of integer type, otherwise the comparison does not have sense.
Therefore, the function someFunction seems accepting as input a logical array.
As an example, with
y = [10 2 10 7 1 3 6 10 10 2]
and
x=10
the code
(y == x)
returns the logical array:
1 0 1 0 0 0 0 1 1 0
This will be the input someFunction function.
Hope this helps,
QWapla'

[kdb+/q]: Convert adjacency matrix to adjacency list

Given (rectangular) adjacency matrix m, how to construct adjacency list in q language?
In QIdioms wiki I've found solution in the k language which when run through q console with k) command gives me 'vs error:
m:(1 0 1;1 0 1)
k) (^m)_vs &,/m
'vs
Result should be:
0 0 1 1
0 2 0 2
This is what I was able to replicate in q:
k) &,/m
0 2 3 5
q) where raze m
0 2 3 5
k's^ a.k.a. shape verb is missing in q so I just did:
k) (^m)
000b
000b
q) 2 3#0b
000b
000b
Now, since:
q) parse "vs"
k) {x\:y}
I tried unsuccessfully both:
q) (2 3#0b) _vs where raze m
'
q) (2 3#0b) _\: where raze m
'type
Note that QIdioms wiki has q solution for inverse problem: from adj.list to adj.matrix.
You've got errors because original Q idioms are written in k2 - an old version of k which modern kdb+ version don't support. A current version of k is k4 and it's not backwards-compatible with k2.
For instance, X _vs Y where X and Y are integer atoms or lists in old k2 behaved like X vs Y will behave in kdb+ starting from 3.4t 2015.12.13: http://code.kx.com/q/ref/lists/#vs:
Since 3.4t 2015.12.13: For integer types, computes the base representation of Y in the radices X.
Another example. Indeed ^ in k2 was a shape operator, but it is not any longer. In k2 ^m would have returned 2 3 for a matrix m from your example whereas current implementation behaves like q's not null as far as I understand.
Now, back to your original question, "how to construct adjacency list in q language". One way to do it is this:
q)lm:{flip raze(til count x),''where each x}
or
k)lm:{+,/(!#x),''&:'x}
UPDATE: Here's how it works. If we were to build an adjacency list using any "verbose" language we would do something like this:
for i = 0 to <number of rows> - 1 <---- (1)
for j = 0 to <number of columns> - 1 <---- (2)
if M[i;j] <> 0 <---- (3)
print i, j
In an array language like q (1) can be "translated" into til count M because count will return the number of elements at top level, i.e. the number of rows. (2) and (3) combined can be represented by where each M. Indeed, for every row we return positions of non-zero elements. Given an original matrix m we will get:
til count m -> 0 1
where each m -> (0 2; 0 2)
All we need to do is join row and column indexes. We can't use just ,' because it will join 0 with the first 0 2 and 1 with the second 0 2 resulting in (0 0 2; 1 0 2). We need to go one level deeper, joining every element from the left with every element of every element of a nested list (0 2; 0 2) from the right, hence double apostrophes in ,''.
I hope it makes sense now.
Personally, I would not use flip (or + in k), I can't read an adjacency matrix in this form:
0 0 1 1
0 2 0 2
I think this is much more readable:
0 0
0 2
1 0
1 2
But it's up to you of course.

Function plot from points result of other function combinations

I have 2 functions declared in wxmaxima: f1(x, y) and f2(x, y). Both contain if-then-else statements and basic arithmetic operations: addition, subtraction, multiplication and division.
For example (just an example, real functions look much more complicated):
f1(x, y) := block([],
if x * y < 123 then x + y
else if x / y > 7 then x - y
);
In both functions x and y change from 0.1 to 500000.
I need a 3D plot (graph) of the following points:
(x, y, z), where f1(x, y) == f2(z, x)
Note that it's impossible to extract z out from the equation above (and get a new shiny function f3(x, y)), since f1 and f2 are too complex.
Is this something possible to achieve using any computational software?
Thanks in advance!
EDIT:
What I need is the plot for
F(x, y, z) = 0
where
F(x, y, z) = f1(x, y) - f2(z, x)
For Maxima, try implicit_plot(f1(x, y) = f2(x, y), [x, <x0>, <x1>], [y, <y0>, <y1>]) where <x0>, <x1>, <y0>, <y1> are some floating point numbers which are the range of the plot. Note that load(implicit_plot) is needed since implicit_plot is not loaded by default.
As an aside, I see that your function f1 has the form if <condition1> then ... else if <condition2> then ... and that's all. That means if both <condition1> and <condition2> are false, then the function will return false, not a number. Either you must ensure that the conditions are exhaustive, or put else ... at the end of the if so that it will return a number no matter what the input.
set = Table[{i,j,0},{i,1,10},{j,0,10}];
Gives a list of desired x and y values and use those with a replace all /.
set = set /.{a_ ,b_ ,c_} -> {a,b, f1[a,b] - f2[a,b]} (*Simplified of course*)
Set is a 2d list of lists so it needs to be flattened by 1 dimension.
set = Flatten[set,1];
ListPlot3D[set (*add plot options*)]

Levenshtein Distance Formula in CoffeeScript?

I am trying to create or find a CoffeeScript implementation of the Levenshtein Distance formula, aka Edit Distance. Here is what I have so far, any help at all would be much appreciated.
levenshtein = (s1,s2) ->
n = s1.length
m = s2.length
if n < m
return levenshtein(s2, s1)
if not s1
return s2.length
previous_row = [s2.length + 1]
for c1, i in s1
current_row = [i + 1]
for c2, j in s2
insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1
substitutions = previous_row[j] # is this unnescessary?-> (c1 != c2)
current_row.push(Math.min(insertions,deletions,substitutions))
previous_row = current_row
return previous_row[previous_row.length-1]
#End Levenshetein Function
Btw: I know this code is wrong on many levels, I am happy to receive any and all constructive criticism. Just looking to improve, and figure out this formula!
CodeEdit1: Patched up the errors Trevor pointed out, current code above includes those changes
Update: The question I am asking is - how do we do Levenshtein in CoffeeScript?
Here is the 'steps' for the Levenshtein Distance Algorithm to help you see what I am trying to accomplish.
Steps
1
Set n to be the length of s.
Set m to be the length of t.
If n = 0, return m and exit.
If m = 0, return n and exit.
Construct a matrix containing 0..m rows and 0..n columns.
2
Initialize the first row to 0..n.
Initialize the first column to 0..m.
3 Examine each character of s (i from 1 to n).
4 Examine each character of t (j from 1 to m).
5 If s[i] equals t[j], the cost is 0.
If s[i] doesn't equal t[j], the cost is 1.
6 Set cell d[i,j] of the matrix equal to the minimum of:
a. The cell immediately above plus 1: d[i-1,j] + 1.
b. The cell immediately to the left plus 1: d[i,j-1] + 1.
c. The cell diagonally above and to the left plus the cost: d[i-1,j-1] + cost.
7 After the iteration steps (3, 4, 5, 6) are complete, the distance is found in cell d[n,m].
source:http://www.merriampark.com/ld.htm
This page (linked to from the resource you mentioned) offers a JavaScript implementation of the Levenshtein distance algorithm. Based on both that and the code you posted, here's my CoffeeScript version:
LD = (s, t) ->
n = s.length
m = t.length
return m if n is 0
return n if m is 0
d = []
d[i] = [] for i in [0..n]
d[i][0] = i for i in [0..n]
d[0][j] = j for j in [0..m]
for c1, i in s
for c2, j in t
cost = if c1 is c2 then 0 else 1
d[i+1][j+1] = Math.min d[i][j+1]+1, d[i+1][j]+1, d[i][j] + cost
d[n][m]
It seems to hold up to light testing, but let me know if there are any problems.