extracting elements of vector of named tuples into matrix in Julia - function

Suppose results is a vector of tuple with length M where typeof(result) = Vector{NamedTuple{(:x, :p, :step), Tuple{Vector{Float64}, Float64, Int64}}}.
p is also a vector of length N where typeof(results[1].p) = Vector{Float64}. I want to extract the first N-1 elements of all the p inside results and express it as an M x (N-1) matrix. I know how to do it in a for loop, but is there a more element way of doing it?

These should both do what you ask but they return an (N-1 x M) matrix and I think they are very similar
hcat(map(x->x.p[1:N-1], results)...)
hcat([x.p[1:N-1] for x in results]...)
For the (M x N-1) output
vcat(map(x->x.p[1:N-1]', results)...)
vcat([x.p[1:N-1]' for x in results]...)
should work but it is a bit slower.

The conventional 2-loop comprehension may be 10X faster than vcat for this. You get an M x (N-1) matrix directly.
[results[i].p[j] for i=1:M, j=1:N-1]

Related

Prepping the number of inputs for a function in MATLAB

For example, ndgrid has inputs as n vectors where n is decided by the user.
For my use case, n can change. I would like to prepare the input list before hand, based on n, then feed the inputs to ndgrid. How do I do that please?
For example, say I have 3 row vectors x1, x2, and x3. Then, if n=3 and I put inputs = [x1,x2,x3], and I use ndgrid(inputs) then MATLAB treats this as ndgrid([x1,x2,x3]) instead of ndgrid(x1,x2,x3). I want the latter, not the former. How do I solve this please?
When we use a cell array, for example x = {some,stuff,inside} you can unpack the cell with x{:}, in a function call, each elements of the cell will be passed as an argument: myfunction(x{:}) is equivalent to myfunction(some, stuff, inside).
In your case:
% Number of inputs
k = 3;
% Put your k input in a cell array
x = {1:3,1:3,1:3};
% If needed you can also have a dynamic output variable
X = cell(k,1);
% Get the result
[X{:}] = ndgrid(x{:})

Fastest way to create mapped matrix in numpy

I have the following problem. I have a 2D numpy matrix of integers, let's say they're in the range 0-19. The matrix has shape (r, c). Call this matrix M. I have an additional array, a lookup table, A, of length 19 whose elements are small numpy vectors, each with length N. What I want to do is to create a new matrix of shape (r, c, N) where I've replaced the integer in the original matrix by it's lookup table counterpart.
Simple enough, it's just a function on a matrix which produces a new matrix with an additional dimension. I have written code for this which looks like:
num_rows, num_cols = M.shape
result = np.zeros(num_rows, num_cols, 3)
for col in range(num_cols):
for row in range(num_ros):
idx = M[row, col]
result[row, col] = np.array(A[idx])
This works but the problem is it's is too slow. If M has 500,000 elements then it takes like 600ms per matrix which is the bottleneck in my code. There has to be a clever numpy way of handling this which is faster but I can't think of it.

F# function composition where the first function has arity >1

I have two functions f and g:
let f (x:float) (y:float) =
x * y
let g (x:float) =
x * 2.0
I want to compose (>>) them to get a new function that performs f and then g on the result.
The solution should behave like:
let h x y =
(f x y) |> g
This does not work:
// Does not compile
let h =
f >> g
How should >> be used?
I think you want to achieve this:
let fog x = f x >> g
You can't compose them directly f >> g in that order, it makes sense since f expects two parameters, so doing f x will result in a partially applied function, but g expects a value, not a function.
Composing the other way around works and in your specific example you get even the same results, because you are using commutative functions. You can do g >> f and you get a composition that results in a partially applied function since g expects a single value, so by applying a value to g you get another value (not a function) and f expects two values, then you will get a partially applied function.
Writing in point-free style, i.e. defining functions without explicit arguments, can become ugly when the implicit arguments are more than one.
It can always be done, with the correct combination of operators. But the outcome is going to be a disappointment and you will lose the primary benefit of point-free style - simplicity and legibility.
For fun and learning, we'll give it a try. Let's start with the explicit (a.k.a. "pointful") style and work from there.
(Note: we're going to rearrange our composition operators into their explicit form (>>) (a) (b) rather than the more usual a >> b. This will create a bunch of parentheses, but it will make things easier to grok, without worrying about sometimes-unintuitive operator precedence rules.)
let h x y = f x y |> g
let h x = f x >> g
// everybody puts on their parentheses!
let h x = (>>) (f x) (g)
// swap order
let h x = (<<) (g) (f x)
// let's put another pair of parentheses around the partially applied function
let h x = ((<<) g) (f x)
There we are! See, now h x is expressed in the shape we want - "pass x to f, then pass the result to another function".
That function happens to be ((<<) g), which is the function that takes a float -> float as argument and returns its composition with g.
(A composition where g comes second, which is important, even if in the particular example used it doesn't make a difference.)
Our float -> float argument is, of course, (f x) i.e. the partial application of f.
So, the following compiles:
let h x = x |> f |> ((<<) g)
and that can now be quite clearly simplified to
let h = f >> ((<<) g)
Which isn't all that awful-looking, when you already know what it means. But anybody with any sense will much rather write and read let h x y = f x y |> g.

Matlab - how to make this work for both scalars and vectors

Suppose function g takes a function f as a parameter, and inside g we have something like
x = t*feval(f, u);
however, f can be either scalar-valued or vector-valued. If it is vector valued, we want x to be a vector as well, i.e. the feval statement to return the whole vector returned by f. How do we make this work for both scalar and vector cases?
As far as I can tell, what you are asking is already the default behavior in matlab.
This means that if f returns a scalar, x will be a scalar and if it returns a vector x will be a vector.
In your example, this holds as long as t is also a scalar - otherwise the result will depend on how t*[output of f] is evaluated.
Example
function o1 = f(N)
o1 = zeros(1,N);
end
Here f returns a scalar if N=1 and a vector for N>1.
Calling your code gives
x=feval('f', 1); % Returns x = 0
x=feval('f', 4); % Returns x = [0 0 0 0]
If the output of feval(f,u) can be either a scalar or a vector, and you want the result x to be the same (i.e. a scalar or a vector of the same length and dimension), then it will depend on what t is:
If t is a scalar, then what you have is fine. You can use either of the operators * or .* to perform the multiplication.
If t is a vector of the same length and dimension as the result from feval(f,u), then use the .* operator to perform element-wise multiplication.
If t is a vector of the same length but with different dimension that the result from feval(f,u) (i.e. one is a row vector and one is a column vector), then you have to make the dimensions match by transposing one or the other with the .' operator.
If t is a different length than the result of feval(f,u), then you can't do element-wise multiplication.

Finding points on a line with a given distance

I have a question i know a line i just know its slope(m) and a point on it A(x,y) How can i calculate the points(actually two of them) on this line with a distance(d) from point A ???
I m asking this for finding intensity of pixels on a line that pass through A(x,y) with a distance .Distance in this case will be number of pixels.
I would suggest converting the line to a parametric format instead of point-slope. That is, a parametric function for the line returns points along that line for the value of some parameter t. You can represent the line as a reference point, and a vector representing the direction of the line going through that point. That way, you just travel d units forward and backward from point A to get your other points.
Since your line has slope m, its direction vector is <1, m>. Since it moves m pixels in y for every 1 pixel in x. You want to normalize that direction vector to be unit length so you divide by the magnitude of the vector.
magnitude = (1^2 + m^2)^(1/2)
N = <1, m> / magnitude = <1 / magnitude, m / magnitude>
The normalized direction vector is N. Now you are almost done. You just need to write the equation for your line in parameterized format:
f(t) = A + t*N
This uses vector math. Specifically, scalar vector multiplication (of your parameter t and the vector N) and vector addition (of A and t*N). The result of the function f is a point along the line. The 2 points you are looking for are f(d) and f(-d). Implement that in the language of your choosing.
The advantage to using this method, as opposed to all the other answers so far, is that you can easily extend this method to support a line with "infinite" slope. That is, a vertical line like x = 3. You don't really need the slope, all you need is the normalized direction vector. For a vertical line, it is <0, 1>. This is why graphics operations often use vector math, because the calculations are more straight-forward and less prone to singularities.
It may seem a little complicated at first, but once you get the hang of vector operations, a lot of computer graphics tasks get a lot easier.
Let me explain the answer in a simple way.
Start point - (x0, y0)
End point - (x1, y1)
We need to find a point (xt, yt) at a distance dt from start point towards end point.
The distance between Start and End point is given by d = sqrt((x1 - x0)^2 + (y1 - y0)^2)
Let the ratio of distances, t = dt / d
Then the point (xt, yt) = (((1 - t) * x0 + t * x1), ((1 - t) * y0 + t * y1))
When 0 < t < 1, the point is on the line.
When t < 0, the point is outside the line near to (x0, y0).
When t > 1, the point is outside the line near to (x1, y1).
Here's a Python implementation to find a point on a line segment at a given distance from the initial point:
import numpy as np
def get_point_on_vector(initial_pt, terminal_pt, distance):
v = np.array(initial_pt, dtype=float)
u = np.array(terminal_pt, dtype=float)
n = v - u
n /= np.linalg.norm(n, 2)
point = v - distance * n
return tuple(point)
Based on the excellent answer from #Theophile here on math stackexchange.
Let's call the point you are trying to find P, with coordinates px, py, and your starting point A's coordinates ax and ay. Slope m is just the ratio of the change in Y over the change in X, so if your point P is distance s from A, then its coordinates are px = ax + s, and py = ay + m * s. Now using Pythagoras, the distance d from A to P will be d = sqrt(s * s + (m * s) * (m * s)). To make P be a specific D units away from A, find s as s = D/sqrt(1 + m * m).
I thought this was an awesome and easy to understand solution:
http://www.physicsforums.com/showpost.php?s=f04d131386fbd83b7b5df27f8da84fa1&p=2822353&postcount=4