How to find this solution with matlab? - matlab

I'm beginner at matlab, and I'm interested how to find the solution of equation :
2x + y <= 6
4x + 5y <= 20
x + 2y >= 4
5x + 3y <= 15
x - 2y + 6 <= 0
how to graph this equation in matlab?
Thanks in advance

In response to some of the comments, I want to say that it does make sense to have these 5 equations in 2 unknowns. First of all, these are inequalities, not equalities. Each of them represent half side of the 2D plane after being cut by a line (all different lines). And your solution to this system of inequality is just the area that is intersection of all these half planes. It could be a closed polygon region, or an unbounded region, or empty set.
Since this looks like an assignment question, I'm not gonna given you the solution here. But here's a hint, densely sample points from XY plane, and for each point, if it satisfies all the equations, plot it, otherwise don't ...
P.S. even if there are all equalities, the system of more linear equations than variables still make sense. It's an overdetermined system, and there is solution in the "least square" sense, i.e. line fit to lots of noisy data with the lowest sum of squared error. But this is not your scenario.

This can be solved by a simplex (optimization method, linear programming) which is totally deterministic hence a computer can achieve the job. Matlab provide tools for this such as linprog. Inequations are your constraints and will define a convex polytope which can be bounded, unbounded or empty. And your goal function is equals to 1.

Related

Symmetric Regression In Stan

I have to vectors of data points (Gene expression in Tissue A and B) and I want to see, if their is any systematic bias along its magnitude (same expression of Gene X in A and B).
The idea was to build a simple regression model in stan and see how much the posterior for the slope (beta) overlaps with 1.
model {
for (n in 1:N){
y[n] ~ normal(alpha[i[n]] + beta[i[n]] * x[n], sigma[i[n]]);
}
}
However, depending on which vector is x and which is y, I get different results, where one slope is about 1 and other not (see Image, where x and y a swapped and the colored lines represents the regressions I get from the model (gray is slope 1)). As I found out, this a typical thing for regression methods like ordinary least squares, which makes sense if one value is dependent on the other. However, here there is no dependency and both vectors are "equal".
Now the question is, what would be an appropriate model to perform a symmetrical regression in stan.
Following the suggestion from LukasNeugebauer by standardizing the data first and working without an intercept, does not solve the problem.
I cheated a bit and found a solution:
When you rotate the coordinate system by 45 degrees, the new y-Axis (y') represents the information of x and y in equal amounts. Therefor, assuming a variance only on the new y-Axis involves both x and y.
x' = x*cos((pi/180)*45) + y*sin((pi/180)*45)
y' = -x*sin((pi/180)*45) + y*cos((pi/180)*45)
The above model now results in symmetric results. Where a slope of 0, represents a slope of 1 in the old system.

Solving integral in Matlab containing unknown variables?

The task is to create a cone hat in Matlab by creating a developable surface with numerical methods. There are 3 parts of which I have done 2. My question is regarding part 3 where I need to calculate the least rectangular paper surface that can contain the hat. And I need to calculate the material waste of the paper.
YOU CAN MAYBE SKIP THE LONG BACKGROUND AND GO TO LAST PARAGRAPH
BACKGROUND:
The cone hat can be created with a skewed cone with its tip located at (a; 0; b) and with a circle-formed base.
x = Rcos u,
y = Rsin u
z = 0
0<_ u >_2pi
with
known values for R, a and b
epsilon and eta ('n') is the curves x- and y- values when the parameter u goes from 0 to 2pi and alpha is the angle of inclination for the curve at point (epsilon, eta). Starting values at A:
u=0, alhpa=0, epsilon=0, eta=0.
Curve stops at B where the parameter u has reached 2pi.
1.
I plotted the curve by using Runge-Kutta-4 and showed that the tip is located at P = (0, sqrt(b^2 + (R-alpha)^2))
2.
I showed that by using smaller intervals in RK4 I still get quite good accuracy but the problem then is that the curve isn't smooth. Therefore I used Hermite-Interpolation of epsilon and eta as functions of u in every interval to get a better curve.
3.
Ok so now I need to calculate the least rectangular paper surface that can contain the hat and the size of the material waste of the paper. If the end angle alpha(2pi) in the template is pi or pi/2 the material waste will be less. I now get values for R & alpha (R=7.8 and alpha=5.5) and my task is to calculate which height, b the cone hat is going to get with the construction-criteria alpha(2pi)=pi (and then for alpha(2pi)=pi/2 for another sized hat).
So I took the first equation above (the expression containing b) and rewrote it like an integral:
TO THE QUESTION
What I understand is that I need to solve this integral in matlab and then choose b so that alpha(2pi)-pi=0 (using the given criteria above).
The values for R and alpha is given and t is defined as an interval earlier (in part 1 where I did the RK4). So when the integral is solved I get f(b) = 0 which I should be able to solve with for example the secant method? But I'm not able to solve the integral with the matlab function 'integral'.. cause I don't have the value of b of course, that is what I am looking for. So how am I going to go about this? Is there a function in matlab which can be used?
You can use the differential equation for alpha and test different values for b until the condition alpha(2pi)=pi is met. For example:
b0=1 %initial seed
b=fsolve(#find_b,b0) %use the function fsolve or any of your choice
The function to be solved is:
function[obj]=find_b(b)
alpha0=0 %initual valur for alpha at u=0
uspan=[0 2*pi] %range for u
%Use the internal ode solver or any of your choice
[u,alpha] = ode45(#(u,alpha) integrate_alpha(u,alpha,b), uspan, alpha0);
alpha_final=alpha(end) %Get the last value for alpha (at u=2*pi)
obj=alpha_final-pi %Function to be solved
end
And the integration can be done like this:
function[dalpha]=integrate_alpha(u,alpha,b)
a=1; %you can use the right value here
R=1; %you can use the right value here
dalpha=(R-a*cos(u))/sqrt(b^2+(R-a*cos(u))^2);
end

Solving equations involving dozens of ceil and floor functions in MATLAB?

I am tackling a problem which uses lots of equations in the form of:
where q_i(x) is the only unknown, c_i, C_j, P_j are always positive. We have two cases, the first when c_i, C_j, P_j are integers and the case when they are real. C_j < P_j for all j
How is this type of problems efficently solved in MATLAB especially when the number of iterations N is between 20 - 100?
What I was doing is q_i(x) - c_i(x) must be equal to the summation of integers. So i was doing an exhaustive search for q_i(x) which satisfies both ends of the equation. Clearly this is computationally exhaustive.
What if c_i(x) is a floating point number, this will even make the problem even more difficult to find a real q_i(x)?
MORE INFO: These equations are from the paper "Integrating Preemption Threshold to Fixed Priority DVS Scheduling Algorithms" by Yang and Lin.
Thanks
You can use bisection method to numerically find zeros of almost any well-behavior functions.
Convert your equation problem into a zero-finding problem, by moving all things to one side of the equal sign. Then find x: f(x)=0.
Apply bisection method equation solver.
That's it! Or may be....
If you have specific range(s) where the roots should fall in, then just perform bisection method for each range. If not, you still have to give a maximum estimation (you don't want to try some number larger than that), and make this as the range.
The problem of this method is for each given range it can only find one root, because it's always picking the left (or right) half of the range. That's OK if P_j is integer, as you can always find a minimum step of the function. Say P_j = 1, then only a change in q_i larger than 1 leads to another segment (and thus a possible different root). Otherwise, within each range shorter than 1 there will be at most one solution.
If P_j is an arbitrary number (such as 1e-10), unless you have a lower limit on P_j, most likely you are out of lucky, since you can't tell how fast the function will jump, which essentially means f(x) is not a well-behavior function, making it hard to solve.
The sum is a step function. You can discretize the problem by calculating where the floor function jumps for the next value; this is periodic for every j. Then you overlay the N ''rhythms'' (each has its own speed specified by the Pj) and get all the locations where the sum jumps. Each segment can have exactly 0 or 1 intersection with qi(x). You should visualize the problem for intuitive understanding like this:
f = #(q) 2 + (floor(q/3)*0.5 + floor(q/4)*3 + floor(q/2)*.3);
xx = -10:0.01:10;
plot(xx,f(xx),xx,xx)
For each step, it can be checked analytically if an intersection exists or not.
jumps = unique([0:3:10,0:4:10,0:2:10]); % Vector with position of jumps
lBounds = jumps(1:end-1); % Vector with lower bounds of stairs
uBounds = jumps(2:end); % Vector with upper bounds of stairs
middle = (lBounds+uBounds)/2; % center of each stair
fStep = f(middle); % height of the stairs
intersection = fStep; % Solution of linear function q=fStep
% Check if intersection is within the bounds of the specific step
solutions = intersection(intersection>=lBounds & intersection<uBounds)
2.3000 6.9000

Detect steps in a Piecewise constant signal

I have a piecewise constant signal shown below. I want to detect the location of step transition (Marked in red).
My current approach:
Smooth signal using moving average filter (http://www.mathworks.com/help/signal/examples/signal-smoothing.html)
Perform Discrete Wavelet transform to get discontinuities
Locate the discontinuities to get the location of step transition
I am currently implementing the last step of detecting the discontinuities. However, I cannot get the precise location and end with many false detection.
My question:
Is this the correct approach?
If yes, can someone shed some info/ algorithm to use for the last step?
Please suggest an alternate/ better approach.
Thanks
Convolve your signal with a 1st derivative of a Gaussian to find the step positions, similar to a Canny edge detection in 1-D. You can do that in a multi-scale approach, starting from a "large" sigma (say ~10 pixels) detect local maxima, then to a smaller sigma (~2 pixels) to converge on the right pixels where the steps are.
You can see an implementation of this approach here.
If your function is really piecewise constant, why not use just abs of diff compared to a threshold?
th = 0.1;
x_steps = x(abs(diff(y)) > th)
where x a vector with your x-axis values, y is your y-axis data, and th is a threshold.
Example:
>> x = [2 3 4 5 6 7 8 9];
>> y = [1 1 1 2 2 2 3 3];
>> th = 0.1;
>> x_steps = x(abs(diff(y)) > th)
x_steps =
4 7
Regarding your point 3: (Please suggest an alternate/ better approach)
I suggest to use a Potts "filter". This is a variational approach to get an accurate estimation of your piecewise constant signal (similar to the total variation minimization). It can be interpreted as adaptive median filtering. Given the Potts estimate u, the jump points are the points of non-zero gradient of u, that is, diff(u) ~= 0. (There are free Matlab implementations of the Potts filters on the web)
See also http://en.wikipedia.org/wiki/Step_detection
Total Variation Denoising can produce a piecewise constant signal. Then, as pointed out above, "abs of diff compared to a threshold" returns the position of the transitions.
There exist very efficient algorithms for TVDN that process millions of data points within milliseconds:
http://www.gipsa-lab.grenoble-inp.fr/~laurent.condat/download/condat_fast_tv.c
Here's an implementation of a variational approach with python and matlab interface that also uses TVDN:
https://github.com/qubit-ulm/ebs
I think, smoothing with a sharper lowpass filter should work better.
Try to use medfilt1() (a median filter) instead, since you have very concrete levels. If you know how long your plateau is, you can take half/quarter of the plateau length for example. Then you would get very sharp edges. The sharp edges should be detectable using a Haar wavelet or even just using simple differentiation.

Find minimum distance between a point and a curve in MATLAB

I would like to use a MATLAB function to find the minimum length between a point and a curve? The curve is described by a complicated function that is not quite smooth. So I hope to use an existing tool of matlab to compute this. Do you happen to know one?
When someone says "its complicated" the answer is always complicated too, since I never know exactly what you have. So I'll describe some basic ideas.
If the curve is a known nonlinear function, then use the symbolic toolbox to start with. For example, consider the function y=x^3-3*x+5, and the point (x0,y0) =(4,3) in the x,y plane.
Write down the square of the distance. Euclidean distance is easy to write.
(x - x0)^2 + (y - y0)^2 = (x - 4)^2 + (x^3 - 3*x + 5 - 3)^2
So, in MATLAB, I'll do this partly with the symbolic toolbox. The minimal distance must lie at a root of the first derivative.
sym x
distpoly = (x - 4)^2 + (x^3 - 3*x + 5 - 3)^2;
r = roots(diff(distpoly))
r =
-1.9126
-1.2035
1.4629
0.82664 + 0.55369i
0.82664 - 0.55369i
I'm not interested in the complex roots.
r(imag(r) ~= 0) = []
r =
-1.9126
-1.2035
1.4629
Which one is a minimzer of the distance squared?
subs(P,r(1))
ans =
35.5086
subs(P,r(2))
ans =
42.0327
subs(P,r(3))
ans =
6.9875
That is the square of the distance, here minimized by the last root in the list. Given that minimal location for x, of course we can find y by substitution into the expression for y(x)=x^3-3*x+5.
subs('x^3-3*x+5',r(3))
ans =
3.7419
So it is fairly easy if the curve can be written in a simple functional form as above. For a curve that is known only from a set of points in the plane, you can use my distance2curve utility. It can find the point on a space curve spline interpolant in n-dimensions that is closest to a given point.
For other curves, say an ellipse, the solution is perhaps most easily solved by converting to polar coordinates, where the ellipse is easily written in parametric form as a function of polar angle. Once that is done, write the distance as I did before, and then solve for a root of the derivative.
A difficult case to solve is where the function is described as not quite smooth. Is this noise or is it a non-differentiable curve? For example, a cubic spline is "not quite smooth" at some level. A piecewise linear function is even less smooth at the breaks. If you actually just have a set of data points that have a bit of noise in them, you must decide whether to smooth out the noise or not. Do you wish to essentially find the closest point on a smoothed approximation, or are you looking for the closest point on an interpolated curve?
For a list of data points, if your goal is to not do any smoothing, then a good choice is again my distance2curve utility, using linear interpolation. If you wanted to do the computation yourself, if you have enough data points then you could find a good approximation by simply choosing the closest data point itself, but that may be a poor approximation if your data is not very closely spaced.
If your problem does not lie in one of these classes, you can still often solve it using a variety of methods, but I'd need to know more specifics about the problem to be of more help.
There's two ways you could go about this.
The easy way that will work if your curve is reasonably smooth and you don't need too high precision is to evaluate your curve at a dense number of points and simply find the minimum distance:
t = (0:0.1:100)';
minDistance = sqrt( min( sum( bxsfun(#minus, [x(t),y(t)], yourPoint).^2,2)));
The harder way is to minimize a function of t (or x) that describes the distance
distance = #(t)sum( (yourPoint - [x(t),y(t)]).^2 );
%# you can use the minimum distance from above as a decent starting guess
tAtMin = fminsearch(distance,minDistance);
minDistanceFitte = distance(tAtMin);