Hope everyone is doing well. Can anyone help me in solving 3 equations involving 2 unknown variables in Matlab?
I tried using symbolic toolbox but it gives me an empty solution. The Matlab code works for 2 equations only. For three equations it gives me an empty solution.
The equation are mentioned below:
cos^2(2\phi) cos(2\theta + sin(2\phi)cos(2\phi) sin(2\theta)=0
sin(2\phi)cos(2\phi)cos(2\theta)+sin^2(2\phi)sin(2\theta)=0
-sin(2\phi)cos(2\theta)+cos(2\phi)sin(2\theta)=0
I want to solve the above equations for theta and phi.
Can anyone help me in solving 3 eq for 2 variables in Matlab, I tried a lot using symbolic tool box but it gives me empty solution. The Matlab code works for 2 equation only. For three equation gives me empty solution.
The simplest explanation is that what Matlab is telling you is correct: there is no solution for the system of three equations.
One way to find out what's happening is to plot the solutions for the three equations individually. First take each equation and define the left side as a function in Matlab:
fun1 = #(phi, theta) cos(2*phi).^2 .* cos(2*theta) + sin(2*phi) .* cos(2*phi) .* sin(2*theta);
fun2 = #(phi, theta) sin(2*phi) .* cos(2*phi) .* cos(2*theta) + sin(2*phi).^2 .* sin(2*theta);
fun3 = #(phi, theta) -sin(2*phi) .* cos(2*theta) + cos(2*phi) .* sin(2*theta);
Now you can use ezplot(fun1) to plot the solutions to the implicit function fun1(x,y)=0. The solutions will be curves in the (theta, phi) plane. If you do this for fun2 and fun3 as well, the simultaneous solution will be represented by places where the curves from all three functions simultaneously intersect.
I don't know how to pile up three the three ezplot plots on the same axes, but we can use contour to accomplish the same thing:
x = linspace(-pi/2, pi/2, 180);
y = linspace(-pi/2, pi/2, 180);
[X, Y] = meshgrid(x, y);
contour(X, Y, fun1(X, Y), [0, 0], 'r', 'linewidth', 3);
hold all
contour(X, Y, fun2(X, Y), [0, 0], 'b');
contour(X, Y, fun3(X, Y), [0, 0], 'g');
hold off
legend('f_1(\theta,\phi)=0','f_2(\theta,\phi)=0','f_3(\theta,\phi)=0');
xlabel('\phi');
ylabel('\theta');
Which produces this graph:
We see that there are no points where the red, blue, and green curves (corresponding to solutions of fun1(x,y)=0, fun2(x,y)=0, and fun3(x,y)=0, respectively) simultaneously intersect.
Thus your system of three equations has no solution.
Related
I have generated a 3D plot that resembles Gaussian distribution, with random variables Y, X1, and X2 (1000x1) vectors. Y is on the vertical axis, X1, and X2 are horizontal.
Specifically, this is the code I used for the plot:
plot3(x(:,1),x(:,2),y,'.')
The graph that has been created has this form:
What I also want to produce is something like that:
But, when I use this code:
contour(x(:,1),x(:,2),y);
I receive a message that:
Error using contour (line 48)
Z must be at least a 2x2 matrix.
I really don't get how to fix that problem, I assume Z is the Y but I don't understand why it has to be 2x2 at least. Anyhow, any help would be much appreciated.
You cannot create a contour over scattered data, you need a grid. It is possible to interpolate the data on a grid of NxN samples in the XY domain, using griddata (here the domain is [-2,2]x[-2,2] as an example):
N = 200;
xi = linspace(-2, 2, N);
yi = linspace(-2, 2, N);
[XI, YI] = meshgrid(xi, yi);
ZI = griddata(x(:,1), x(:,2), y, XI, YI, 'v4');
contour(XI,YI,ZI);
More info on how to interpolate scattered data here.
This is my primer time using matlab especially plotting.
I try to plot the solutions for y = x^2 − x − 2 like in here
But I don't know how to model this plot in matlab (it makes sense because the solutions must be computed first) but shouldn't the shape of curve will remain the same.
I tried:
clc;
close all;
%y = x2 − x − 2
x = [-3:1:3];
y= x.^2 - x -2;
plot(y), grid on;
But the curve I got is totally different.
You're choosing wrong points for drawing the curve.
The image that you showed above takes the values of x in the interval [-2,3]. Fixing this gives exactly the same curve as that of the one in the question.
Also note that the minima of your function is at x=0.5. So, if x has equal number of values less than 0.5 and greater than 0.5, you will get the curve of the desired shape.
Code:
x = [-2:0.01:3]; %Choosing 0.01, because more the points, more the curve will be accurate
y= x.^2 - x -2;
plot(x,y), grid on;
Output:
I have a question, because this work for many functions, but I have a trouble when trying to plot the integral of a sine (I am using matlab 2010):
clear all
close all
clc
x = linspace(-10, 10, 100);
f = #(x) sin(x);
I = arrayfun(#(x) quad(f, 0, x), x);
plot(x, f(x),'r', x, I, 'b')
I expect having a -cos(x), but instead I get something with an offset of 1, why is this happening? How should fix this problem?
The Fundamental Theorem of Calculus says that the indefinite integral of a nice function f(x) is equal to the function's antiderivative F(x), which is unique up-to an additive constant. Further, a definite integral has the form:
In this form, the constant of integration will cancel out, and the integral will exactly equal the desired antiderivative only if the lower bound evaluation vanishes. However, -cos(0) does not vanish and has a value of -1. So in order to calculate the desired antiderivative F(x), the lower bound evaluation should be added to the right-hand side.
plot(x, f(x),'r', x, I+ (-cos(0)), 'b');
This is the equivalent of assigning an initial value for the solution of ODEs a la ode45.
What you're trying to do can be achieved using the following:
x = linspace(-10, 10, 100);
syms y;
f = sin(y) %function
I =int(f,y) %integration of f
plot(x, subs(f,y,x),'r', x, subs(I,y,x), 'b')
Output:-
According to Matlab documentation, q = quad(fun,a,b)
Quadrature is a numerical method used to find the area under the graph of a function, that is, to compute a definite integral.
Integral of sin(x) equals -cos(x)
Definite integral of sin(x) from x = pi to x = 0:
-cos(pi) - (-cos(0)) = 2
Since quad compute a definite integral, I can't see any problem.
Same as:
figure;plot(-cos(x) - (-cos(0)))
I have a set of 3d data (300 points) that create a surface which looks like two cones or ellipsoids connected to each other. I want a way to find the equation of a best fit ellipsoid or cone to this dataset. The regression method is not important, the easier it is the better. I basically need a way, a code or a matlab function to calculate the constants of the elliptic equation for these data.
You can also try with fminsearch, but to avoid falling on local minima you will need a good starting point given the amount of coefficients (try to eliminate some of them).
Here is an example with a 2D ellipse:
% implicit equation
fxyc = #(x, y, c_) c_(1)*x.^2 + c_(2).*y.^2 + c_(3)*x.*y + c_(4)*x + c_(5).*y - 1; % free term locked to -1
% solution (ellipse)
c_ = [1, 2, 1, 0, 0]; % x^2, y^2, x*y, x, y (free term is locked to -1)
[X,Y] = meshgrid(-2:0.01:2);
figure(1);
fxy = #(x, y) fxyc(x, y, c_);
c = contour(X, Y, fxy(X, Y), [0, 0], 'b');
axis equal;
grid on;
xlabel('x');
ylabel('y');
title('solution');
% we sample the solution to have some data to fit
N = 100; % samples
sample = unique(2 + floor((length(c) - 2)*rand(1, N)));
x = c(1, sample).';
y = c(2, sample).';
x = x + 5e-2*rand(size(x)); % add some noise
y = y + 5e-2*rand(size(y));
fc = #(c_) fxyc(x, y, c_); % function in terms of the coefficients
e = #(c) fc(c).' * fc(c); % squared error function
% we start with a circle
c0 = [1, 1, 0, 0, 0];
copt = fminsearch(e, c0)
figure(2);
plot(x, y, 'rx');
hold on
fxy = #(x, y) fxyc(x, y, copt);
contour(X, Y, fxy(X, Y), [0, 0], 'b');
hold off;
axis equal;
grid on;
legend('data', 'fit');
xlabel('x'); %# Add an x label
ylabel('y');
title('fitted solution');
The matlab function fit can take arbitrary fit expressions. It takes a bit of figuring out the parameters but it can be done.
You would first create a fittype object that has a string representing your expected form. You'll need to work out the expression yourself that best fits what you're expecting, I'm going to take a cone expression from the Mathworld site for an example and rearrange it for z
ft = fittype('sqrt((x^2 + y^2)/c^2) + z_0', ...
'independent', {'x', 'y'}, 'coeff', {'c', 'z_0'});
If it's a simple form matlab can work out which are the variables and which the coefficients but with something more complex like this you'd want to give it a hand.
The 'fitoptions' object holds the configuration for the methods: depending on your dataset you might have to spend some time specifying upper and lower bounds, starting values etc.
fo = fitoptions('Upper', [one, for, each, of, your, coeffs, in, the, order, they, appear, in, the, string], ...
'Lower', [...], `StartPoint', [...]);
then get the output
[fitted, gof] = fit([xvals, yvals], zvals, ft, fo);
Caveat: I've done this plenty with 2D datasets and the docs state it works for three but I haven't done that myself so the above code might not work, check the docs to make sure you've got your syntax right.
It might be worth starting with a simple fit expression, something linear, so that you can get your code working. Then swap the expression out for the cone and play around until you get something that looks like what you're expecting.
After you've got your fit a good trick is that you can use the eval function on the string expression you used in your fit to evaluate the contents of the string as if it was a matlab expression. This means you need to have workspace variables with the same names as the variables and coefficients in your string expression.
Dx=y
Dy=-k*y-x^3+9.8*cos(t)
inits=('x(0)=0,y(0)=0')
these are the differential equations that I wanted to plot.
first, I tried to solve the differential equation and then plot the graph.
Dsolve('Dx=y','Dy=-k*y-x^3+9.8*cos(t)', inits)
like this, however, there was no explicit solution for this system.
now i am stuck :(
how can you plot this system without solving the equations?
First define the differential equation you want to solve. It needs to be a function that takes two arguments - the current time t and the current position x, and return a column vector. Instead of x and y, we'll use x(1) and x(2).
k = 1;
f = #(t,x) [x(2); -k * x(2) - x(1)^3 + 9.8 * cos(t)];
Define the timespan you want to solve over, and the initial condition:
tspan = [0, 10];
xinit = [0, 0];
Now solve the equation numerically using ode45:
ode45(f, tspan, xinit)
which results in this plot:
If you want to get the values of the solution at points in time, then just ask for some output arguments:
[t, y] = ode45(f, tspan, xinit);
You can plot the phase portrait x against y by doing
plot(y(:,1), y(:,2)), xlabel('x'), ylabel('y'), grid
which results in the following plot