I am self-studying Introduction to algorithms, and am confused by the answer to 22.1-7.
Consider a directed graph with no self loop. I think it can be like picture3,
so the incidence matrix B should be
picture4
and the BT should be picture5
so The product of BBT should be picture6
i can understand the value in the diagonal means the the number of edge connect with the point
but in BBT[1][4] the value is 1 (0*1+(-1)*(-1)+(-1)*0)
i confused and don’t understand what wrong with it
To begin with, I think it's excellent that you actually tried to verify it with an example.
Unfortunately, you don't specify your edge numbers, so it's unclear what your incidence matrix refers to.
Suppose we use the following numbering:
Then the incidence matrix is
import numpy as np
b = np.array([[-1, -1, 0], [1, 0, 1], [0, 1, -1]])
>>> b
array([[-1, -1, 0],
[ 1, 0, 1],
[ 0, 1, -1]]
And the product is
>>> np.dot(b, b.T)
array([[ 2, -1, -1],
[-1, 2, -1],
[-1, -1, 2]])
which does not seem to be what you got, but actually makes a lot of sense.
Related
My problem is as follows:
Given n points on a line segment and a threshold k, pick the points on the line so that would minimize the average difference of the distance between each consecutive point and the threshold.
For example:
If we were given an array of points n = [0, 2, 5, 6, 8, 9], k = 3
Output: [0, 2, 6, 9]
Explanation: when we choose this path, the difference from the threshold in each interval is [1, 1, 0] which gets an average of .66 difference.
If I chose [0, 2, 5, 8, 9], the differences would be [1, 0, 0, 2], which averages to .75.
I understand enough dynamic programming to consider several solutions including memorization and depth-first search, but I was hoping someone could offer a specific algorithm with the best efficiency.
It is known that Knuth's Algorithm X or Dancing Links is used to resolve exact cover problem. But now I have a problem similar with exact cover.
The problem has some overlapped area, different from exact cover. In exact cover, all coverage’s height/weight is 1. But in my problem, the coverage may has different heights (always a positive integer less than 4).
For example, I just want to find the subsets from a gave sets to cover with S [ 2, 1, 3]:
Now, A [1,0,2] and B [1,1,1] are the expected subsets.
S = [2, 1, 3]
A = [1, 0, 2]
B = [1, 1, 1]
C = [0, 1, 0]
D = [1, 1, 0]
Any clue or pager, thank you very much~
When I tried to use the function "solve" in gem NMatrix, I find wrong result...
I am trying to solve the linear system a*x = b where
a = [[1, 0, 0],
[4, -5, 1],
[0, 0, 1]]
and
b = [0, 0, 729]
Which should give the answer
x = [0, 145.8, 729]
I call the solve function doing a.solve(b) (as explained at http://www.rubydoc.info/gems/nmatrix/0.2.1/NMatrix#solve-instance_method) but it returns
x = [0, 1.013500790889141e-30, 1.013500790889141e-30]
Therefore, I have two questions:
Am I doing something wrong?
If not, what would be the other solution (excluding GSL) to solve matrix systems with ruby?
Thank you !
To answer part 2 of your question, you can use Ruby's built-in Matrix class.
require 'matrix'
m = Matrix[[1, 0, 0], [4, -5, 1], [0, 0, 1]]
#=> Matrix[[1, 0, 0], [4, -5, 1], [0, 0, 1]]
b = Vector[0, 0, 729]
#=> Vector[0, 0, 729]
a = m.lup.solve(b).to_a
#=> [(0/1), (729/5), (729/1)]
If one prefers floats (rather than rational numbers),
a.map(&:to_f)
#=> [0.0, 145.8, 729.0]
See Matrix#lup and Matrix::LUPDecomposition#solve, which solve the linear system using LU decomposition.
If the system of linear equations has no solution (e.g., [[0,0], [0,0]]*x = b) or an infinite number of solutions (that is, m is singular), Ruby will raise an exception. For example,
Matrix[[0,0],[0,0]].lup.solve [1, 1]
#=> ExceptionForMatrix::ErrNotRegular: Not Regular Matrix
require matrix makes both the Matrix and Vector classes (and subclasses) available for use.
I'm looking for an algorithm that will detect the end of a curved line. I'm going to convert a binary image into a point cloud as coordinates, and I need to find the end of the line so I can start another algorithm.
I was thinking of taking the average of vectors for the N nearest '1' pixels to each point, and saying that the pixel with the longest vector must be an endpoint, because if a point is in the middle of a line then the average of the vectors will cancel out. However, I figure this must be a problem that is well known in image processing so I thought I'd throw it up here to see if anybody knows a 'proper' algorithm.
If the line will only ever be one or perhaps two pixels thick, you can use the approach suggested by Malcolm McLean in a comment.
Otherwise, one way to do this is to compute, for each red pixel, the red pixel in the same component that is furthest away, as well as how far away that furthest pixel is. (In graph theory terms, the distance between these two pixels is the eccentricity of each pixel.) Pixels near the end of a long line will have the greatest eccentricities, because the shortest path between them and points at the other end of the line is long. (Notice that, whatever the maximum eccentricity turns out to be, there will be at least two pixels having it, since the distance from a to b is the same as the distance from b to a.)
If you have n red pixels, all eccentricities (and corresponding furthest pixels) can be computed in O(n^2) time: for each pixel in turn, start a BFS at that pixel, and take the deepest node you find as its furthest pixel (there may be several; any will do). Each BFS runs in O(n) time, because there are only a constant number of edges (4 or 8, depending on how you model pixel connectivity) incident on any pixel.
For robustness you might consider taking the top 10 or 50 (etc.) pixel pairs and checking that they form 2 well-separated, well-defined clusters. You could then take the average position within each cluster as your 2 endpoints.
If you apply thinning to the line, so your line is just one pixel thick, You can leverage morphologyEX and use MORPH_HITMISS in OpenCV. Essentially you create a template (kernel or filter) for every possible corner (there are 8 possible) and convolve by each one. The result of each convolution will be 1 in the place where the kernel matches and 0 otherwise. So you can do the same manually if you feell that you can do a better job in c.
here is an example. It takes as input_image any image of zeros and ones where the lines are one pixel thick.
import numpy as np
import cv2
import matplotlib.pylab as plt
def find_endoflines(input_image, show=0):
kernel_0 = np.array((
[-1, -1, -1],
[-1, 1, -1],
[-1, 1, -1]), dtype="int")
kernel_1 = np.array((
[-1, -1, -1],
[-1, 1, -1],
[1,-1, -1]), dtype="int")
kernel_2 = np.array((
[-1, -1, -1],
[1, 1, -1],
[-1,-1, -1]), dtype="int")
kernel_3 = np.array((
[1, -1, -1],
[-1, 1, -1],
[-1,-1, -1]), dtype="int")
kernel_4 = np.array((
[-1, 1, -1],
[-1, 1, -1],
[-1,-1, -1]), dtype="int")
kernel_5 = np.array((
[-1, -1, 1],
[-1, 1, -1],
[-1,-1, -1]), dtype="int")
kernel_6 = np.array((
[-1, -1, -1],
[-1, 1, 1],
[-1,-1, -1]), dtype="int")
kernel_7 = np.array((
[-1, -1, -1],
[-1, 1, -1],
[-1,-1, 1]), dtype="int")
kernel = np.array((kernel_0,kernel_1,kernel_2,kernel_3,kernel_4,kernel_5,kernel_6, kernel_7))
output_image = np.zeros(input_image.shape)
for i in np.arange(8):
out = cv2.morphologyEx(input_image, cv2.MORPH_HITMISS, kernel[i,:,:])
output_image = output_image + out
return output_image
if show == 1:
show_image = np.reshape(np.repeat(input_image, 3, axis=1),(input_image.shape[0],input_image.shape[1],3))*255
show_image[:,:,1] = show_image[:,:,1] - output_image *255
show_image[:,:,2] = show_image[:,:,2] - output_image *255
plt.imshow(show_image)
So ive taken up Prolog and im trying to learn the ropes of it. Right now im working on a assignment set by the book and ive come quite far. My output nearly matches that which is required but somehow its makes the last few lests that come out come out in a head|tail format in which the tail is a row of dots?
The code ive written looks like this:
%prefix methode. E1 + L = L1
% It takes L, adds E1 in front of it and makes it L1.
prefix(_,[],[]).
prefix(El,[LHead|LTail],[Q|L1]) :- Q = [El|LHead], prefix(El,LTail,L1).
gray(0,[[]]).
gray([],[]).
% this should generate a list of all the gray
% code possibilities with the defined length
gray(N,Lijst) :- N > 0, X is N - 1, gray(X,Prevlist),
reverse(Prevlist, RevPrevlist), prefix(0,Prevlist,Deel1),
prefix(1,RevPrevlist,Deel2), append(Deel1,Deel2,Lijst).
Now the thing it should do is if I give him for example -?gray(3,List).
It should tell me:
List = [[0,0,0],[0,0,1],[0,1,1],[0,1,0],[1,1,0],[1,1,1],[1,0,1],[1,0,0]].
However what it tells me instead is:
List = [[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0], [1, 1, 0], [1, 1, 1], [1, 0|...], [1|...]].
As you can see with the output I get my last two lasts have a head|tail construction with a tail consisting of dots. However I do not know what this means or what I did wrong in my code.
Can anybody elaborate why I am getting the dots, and maybe steer me in the right direction to help me solve the problem?
P.S. my apologies if I might've been unclear on certain parts. If I've been so, please say so and I'll try to edit/elaborate.
I just ran this through on swi-prolog:
2 ?- grey(3, List).
Correct to: "gray(3,List)"? yes
List = [[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0], [1, 1, 0], [1, 1, 1], [1, 0|...], [1|...]] [write]
List = [[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0], [1, 1, 0], [1, 1, 1], [1, 0, 1], [1, 0, 0]]
Notice where it said [write].. I press the 'w' button at that point which forces swi-prolog to dump out the whole list, not just appreviate it with the ...
Not sure if that helps, or if the answer is correct.
If not, suggest explaining the problem/assignment itself in a bit more detail. You've explained your solution in some detail, but it's not clear what the problem is ? To me, anyway.
Edit I see you have edited to clarify.. yep, just looks like prolog was abbreviating the results visually, but was actually holding the correct result. A 'display only' issue.