Plotting function in interval - matlab

I have the following function :
ySol2=(2*(x^3 + 1)^(1/2))/cos(x) +2/cos(x)
my question is how can I draw it in the interval 1000;5000 with the constrains cos(x) != 0 and x> -1?

Something like this perhaps?
% your function. Note element-wise operations (.^, ./)
ySol2 = #(x) (2*(x.^3 + 1).^(1/2))./cos(x) +2./cos(x);
% your x interval, with step 0.1. Note also that the argument for 'cos' is in [rad].
x = 1000:0.1:5000;
% calculate function values
y = ySol2(x);
% keep only non-constrained values
ind = (cos(x)~=0) | (x>-1);
x = x(ind);
y = y(ind);
% plot
figure;
plot(x,y);

Related

Find the minimum of a multi-variable function

Question: Find the minimum of f(x,y)=x^2+y^2-2*x-6*y+14 in the window [0,2]×[2,4] with increment 0.01 for x and y.
My approach: Find the first partial derivatives fx and fy. The critical points satisfy the equations fx(x,y) = 0 and fy(x,y) = 0 simultaneously. find the second order partial derivatives fxx(x,y), fyy(x,y) and fxy(x,y) in order to find D.
clc
clear all
syms x y
fun=x^2+y^2-2*x-6*y+14;
fx=diff(fun,x);
fy=diff(fun,y);
pt=solve(fx==0,fy==0);
sol = struct2array(pt)
fxx=diff(fx,x);
fyy=diff(fy,y);
fxy=diff(fx,y);
D=subs(fxx,[x y],[1 3])*subs(fyy,[x y],[1 3])-(subs(fxy,[x y],[1 3]))^2
fxx_val=subs(fxx,[x y],[1 3])
minimum_value=subs(fun,[x y],[1 3])
Am I doing the right thing about what the question asked? Besides what about the window and increment mentioned that question. Any hints or solution will be appreciated .
Thanks in advance .
Use function evaluation optimization method instead of gradient
Please read through the code
f = #(x,y)x.^2+y.^2-2.*x-6.*y+14;
% x range
x_lb = 0;
x_ub = 2;
% y range
y_lb = 2;
y_ub = 4;
step = 0.01;
% lower bound of x, initial guess as xmin
xmin = x_lb;
% lower bound of y, initial guess as ymin
ymin = y_lb;
% f at the lower bounds, initial fmin
fmin = f(xmin, ymin);
for x = x_lb:step:x_ub
for y = y_lb:step:y_ub
% function evaluation
fval = f(x, y);
%replace fmin if the newly evaluated f is less than the actual fmin
if fval < fmin
fmin = fval;
% save current x and y where f is minimum
xmin = x;
ymin = y;
end
end
end
Solution
xmin = 1;
ymin = 3;
fmin = 4;
I would suggest to make use of Matlab's capabilities to compute with matrices. Then, no loop is required.
% your function, look up anonymous functions
func = #(x,y) x.^2 + y.^2 - 2.*x - 6.*y + 14;
% get matrices for you x- and y-window
[xg, yg] = meshgrid(0:.01:2, 2:0.01:4);
% compute all in one call
result = func(xg,yg);
% find total minimum
minimum = min(result(:));
% find the index of the (first) minimum, for other equations, there might
% be more than one
ind = find(result==minimum, 1);
% Output the result
fprintf('The minimum (%d) is located at x: %d, y: %d.\n', minimum, xg(ind), yg(ind));

Lagrange interpolation perturbation in matlab

This is my code for finding the centered coefficients for lagrange polynomial interpolation:
% INPUT
% f f scalar - valued function
% interval interpolation interval [a, b]
% n interpolation order
%
% OUTPUT
% coeff centered coefficients of Lagrange interpolant
function coeff = lagrangeInterp (f, interval , n)
a = interval(1);
b = interval(2);
x = linspace(a,b,n+1);
y = f(x);
coeff(1,:) = polyfit(x,y,n);
end
Which is called in the following script
%Plot lagrangeInterp and sin(x) together
hold on
x = 0:0.1*pi:2*pi;
for n = 1:1:4
coeff = lagrangeInterp(#(x)sin(x),[0,2*pi],n);
plot(x,polyval(coeff,x,'-'));
end
y = sin(x);
plot(x,y);
legend('1st order','2nd order','3rd order','4th order','sin(x)');
To check for stability I would like to perturb the function (eg g(x) = f(x) + epsilon). How would I go about this?
Well, a little trick for you.
You know randn([m,n]) in matlab generate a m*n random matrix. The point is to generate a random vector, and interp1 to a function of x. Like this:
x = linspace(a,b,n+1); % Your range of input
g = #(ep,xx)f(xx)+interp1(x,ep*randn([length(x),1]),xx);

Extracting x value given y threshold from polyfit plot (Matlab)

As shown by the solid and dashed line, I'd like to create a function where I set a threshold for y (Intensity) from that threshold it gives me corresponding x value (dashed line). Very simple but my while statement is off. Any help would be much appreciated!
%% Curve fit plotting %%
x1 = timeStamps(1:60); % taking timestamps from 1 - 120 given smoothed y1 values
y1 = smooth(tic_lin(1:60),'sgolay',1);
% Find coefficients for polynomial (order = 4 and 6, respectively)
fitResults1 = polyfit(x1',y1, 7);
% evaluate the fitted y-values
yplot1 = polyval(fitResults1,x1');
% interpolates to find yi, the values of the underlying function Y at the points in the vector or array xi. x must be a vector.
Time_points = interp1(yplot1, x1', yplot1);
figure( 'Name', 'Curvefit1_poly' );
h = plot(x1', y1);%smoothed-points
hold on;
plot(x1', yplot1);%polyfit points
hold on;
plot(Time_points, yplot1, '*r');%interpolated points of x given y
%given y-threshold, output x(corresponding time_point).
broken = false;
while broken == false
if yplot1 >= 2024671226502.99
index = find(yplot1);
xDesired = x1(index);
broken = true;
else
disp("next iteration through");
end
end
No while loop is needed here... You can do this with logical indexing for the threshold condition and find to get the first index:
% Start with some x and y data
% x = ...
% y = ...
% Get the first index where 'y' is greater than some threshold
thresh = 10;
idx = find( y >= thresh, 1 ); % Find 1st index where y >= thresh
% Get the x value at this index
xDesired = x( idx );
Note that xDesired will be empty if there was no y value over the threshold.
Alternatively, you already have a polynomial fit, so you could use fzero to get the x value on that polynomial for a given y (in this case your threshold).
% x = ...
% y = ...
thresh = 10;
p = polyfit( x, y, 3 ); % create polynomial fit
% Use fzero to get the root of y = a*x^n + b*x^(n-1) + ... + z when y = thresh
xDesired = fzero( #(x) polyval(p,x) - thresh, x(1) )
Note, this method may give unexpected results if the threshold is not within the range of y.

How to plot a discrete signal in matlab?

I want to plot a function y[n] = x[n+2]. My problem is that it does not plot in right range or even does not draw the zero sample points.
n = 1:6;
x = 1:1:8;
f = figure;
subplot(1,2,1)
stem(n, x(n));
axis([-3,8, 0, 7]);
xlabel('n');
ylabel('x[n]');
title('Subplot 1')
subplot(1,2,2)
stem(n, x(n + 2));
xlabel('n');
ylabel('y[n]');
title('Subplot 2')
How to change the variables n or x to get the right plot?
In the end, it ought to look like this:
You are confusing the concept of indices with your dependent variable. You should construct a function x which transforms an input n using the relationship that you know
function y = x(n)
% Set all outputs to 0
y = zeros(size(n));
% Replace the values that fall between 0 and 6 with their same value
y(n >= 0 & n <= 6) = n(n >= 0 & n <= 6);
end
Then you should pass this function a range of n values to evaluate.
nvalues = -3:8;
yvalues = x(nvalues);
stem(nvalues, yvalues)
You can also apply a transformation to the n values
nvalues = -3:8;
yvalues = x(nvalues + 2);
stem(nvalues, yvalues)

Taylor series approximation when the series is truncated after the first, second and third term, in MATLAB

I want to write an m-file function demoTaylorlog(x0,dx) that does the equivalent but for the Taylor series representation of f(x) = ln(x).
This is what I have, but it does not work. I am not sure if it is the right code. How should I fix it?
function demoTaylorlog(x0,dx)
% demoTaylor Taylor Series approximations for f(x) = 1/(1-x)
%Synopsis:
% demoTaylorlog(x0,dx)
% Input: x0 = (optional) point about which the Taylor Series expansion is
% made. Default: x0 = 1.6;
% dx = (optional) size of neighborhood over which the expansion
% is evaluated. Default: dx = 0.8
% Output: a plot of f(x) and its Taylor Series approximations
if nargin<2, x0 = 1.6; dx = 0.8; end
x = linspace(x0-dx/2,x0+dx/2,20);
% x-values at which f(x) is evaluated
f(x)= log(x);
% Exact f(x); notice the array operator
h = x - x0;
% Avoid recomputing intermediate values,
t = 1/(1-x0);
% h and t p1x = t*ones(size(x)) + h*t^2;
% First order Taylor polynomial p2x = p1x+ (h.^2)*t^3;
% Second order " " " p3x = p2x + (h.^3)*t^4;
% Third
plot(x,fx,'-',x,p1x,'o-',x,p2x,'^-',x,p3x,'s-');
legend('exact','P_1(x)','P_2(x)','P_3(x)',4);
xlabel('x');
ylabel('Approximations to f(x) = 1/(1-x)');
end
In the statement f(x)= log(x); f is a vector and log is a function. Suppose that your x vector is [0.12 0.24 0.36] then the statement with the error is equivalent to:
f(0.12) = log(0.12);
f(0.24) = log(0.24);
f(0.36) = log(0.36);
But if fis a vector the assignment to f(0.12) has no sense because .12 is not a positive integer or a logical value (as the error says).
You should write f = log(x);