I have a question regarding Matlab's option to publish in PDF. Say I have the following code:
%1D functions and plotting
%1. We calculate y given the following function: y(x) = 2x^2 +
%3x + 1, for x = 10.
x = 10;
y = 2*x.^2 + 3*x + 1
%2. We calculate y given the following function: y(x) = ax^2 + bx + c, with a
%=2, b=3, c=0 and x = 100.
a=2;
b=3;
c=0;
x=100;
y = a*x.^2 + b*x + c
. . . more code follows here
When I choose to publish this as PDF the answers to problems 1 and 2 (where I calculate two different values for the variable 'y') do not appear at the line where I calculate the value (where I write y = 2*x.^2 + 3*x + 1 for instance). Instead, the values of the 'y' variables appear at the end of the document where it says 'y = 231' and 'y = 20300'. Is there any way I can get this to be included right after I define the variable without separating the document into cells? Or is this a default thing that I can not do anything about? I would really appreciate any input!
The general approach (indipendent of the output format) is to restart the paragraph with line break and %%:
%% 1. We calculate y given the following function: y(x) = 2x^2 +
% 3x + 1, for x = 10.
x = 10;
y = 2*x.^2 + 3*x + 1
%% 2. We calculate y given the following function: y(x) = ax^2 + bx + c, with a
% =2, b=3, c=0 and x = 100.
a=2;
b=3;
c=0;
x=100;
y = a*x.^2 + b*x + c
Related
I have an equation: y=ax^3 + bx^2 + cx + d and the list of values x = 1, 2, 3, 4 when y = 3, 4, 3, -6 respectively. In Octave, I want to:
(a) Set up a system of four equations involving a, b, c and d. For example, substituting (x, y) = (1,3) into the polynomial gives the equation 3 = a + b + c + d.
(b) Solve the system in (a).
I've been trying to find how to do this for three hours and found nothing. Any help would be appreciated
Thanks.
pstscrpt - I have to do everything in Octave, even though I could find it by hand
Written without any ; at end of assignements so you can see what is going on.
You problem is basically a linear system in the variables [a,b,c,d]'=z
So you need to build a system A*z=y, where A is a matrix 4x4, y and z are column vector size 4
x=[1,2,3,4]'
y=[3,4,3,-6]'
A=zeros(4,4)
for i=1:4
A(i,:)= [ x(i)^3, x(i)^2, x(i), 1]
endfor
z=A\y
the outcome will be
z =
-1.00000
5.00000
-7.00000
6.00000
In Matlab: start by just substituting the different values of x and y you wrote in the expression a*x^3 + b*x^2 + c*x + d = y as:
syms a b c d
eqn1 = a*1^3 + b*1^2 + c*1^1 +d == 3 ;
eqn2 = a*2^3 + b*2^2 + c*2^1 +d == 4 ;
eqn3 = a*3^3 + b*3^2 + c*3^1 +d == 3 ;
eqn4 = a*4^3 + b*4^2 + c*4^1 +d == -6 ;
Then Use equationsToMatrix to convert the equations into the form AX = B. The second input to equationsToMatrix specifies the independent variables in the equations.:
[A,B] = equationsToMatrix([eqn1, eqn2, eqn3, eqn4], [a, b, c,d ])
and the solution for a,b,c,d is:
X = linsolve(A,B)
you can also use if you want
sol = solve([eqn1, eqn2, eqn3, eqn4], [a, b, c,d ])
I am trying to compute the taylor series of ln(x) for any value of x.
What I have so far is:
clear
clc
n = input('Enter number of iiterations (n): ' );
x = input('enter value of x (x): ');
y = zeros(1,n);
for i = 0:n
y(i+1)=sum + (-1)^(n+1)*(x-1)^n/n;
end
But this code seems to be broken and I can't figure out why. Any suggestions on how to improve?
This is a one liner in addition to the for-loop answer provided by #farbiondriven
For 0<x<1 :
sumLn = #(x, n)(sum(((-1).^(0:n-1)).*((x-1).^(1:n))./(1:n)));
sumLn(0.5,10)
ans =
-0.6931
>> log(0.5)
ans =
-0.6931
For x>0.5 :
sumLn = #(x, n)(sum( ((x-1)/x).^(1:n) ./ (1:n) ));
sumLn(2,10)
ans =
0.6931
log(2) =
0.6931
Note: The variable x in this formula is bounded as mentioned in this link.
Try this:
clear
clc
n = input('Enter number of iterations (n): ' );
x = input('enter value of x with abs value < 1 (x): ');
y = zeros(1,n+1);
y(1)=0;
for i = 1:n
y(i+1)= y(i) + ((-1)^(i+1)*(x-1)^i/i);
end
txt = sprintf('The output is: %f', y(n+1))
I suggest using built-in function and hopefully there is one. taylor(f,var) approximates f with the Taylor series expansion of f up to the fifth order at the point var = 0.
Specify Expansion Point :
Find the Taylor series expansions at x = 1 for these functions. The default expansion point is 0. To specify a different expansion point, use 'ExpansionPoint':
syms x
taylor(log(x), x, 'ExpansionPoint', 1)
ans =
x - (x - 1)^2/2 + (x - 1)^3/3 - (x - 1)^4/4 + (x - 1)^5/5 - 1
Specify Truncation Order :
The default truncation order is 6.
syms x
f = log(x);
t6 = taylor(f, x);
Use 'Order' to control the truncation order. For example, approximate the same expression up to the orders 8.
syms x
taylor(log(x), x, 'ExpansionPoint', 1, 'Order', 8);
I have a mathematical function E which I want to minimize. I get from solving this 16 possible solutions x1, x2, ..., x16, only two of which that actually minimize the function (located at a minimum). Using a for loop, I can then plug all of these 16 solutions into the original function, and select the solutions I need by applying some criteria via if statements (plotting E vs E(x) if x is real and positive, if first derivative of E is below a threshold, and if the second derivative of E is positive).
That way I only plot the solutions I'm interested in. However, I would now like to extract the relevant x that I plot. Here's a sample MATLAB code that plots the way I just described. I want to extract the thetas that I actually end up plotting. How to do that?
format long
theta_s = 0.77944100;
sigma = 0.50659500;
Delta = 0.52687700;
%% Defining the coefficients of the 4th degree polynomial
alpha = cos(2*theta_s);
beta = sin(2*theta_s);
gamma = 2*Delta^2/sigma^2;
a = -gamma^2 - beta^2*Delta^2 - alpha^2*Delta^2 + 2*alpha*Delta*gamma;
b = 2*alpha*gamma - 2*Delta*gamma - 2*alpha^2*Delta + 2*alpha*Delta^2 -...
2*beta^2*Delta;
c = 2*gamma^2 - 2*alpha*Delta*gamma - 2*gamma - alpha^2 + 4*alpha*Delta +...
beta^2*Delta^2 - beta^2 - Delta^2;
d = -2*alpha*gamma + 2*Delta*gamma + 2*alpha + 2*beta^2*Delta - 2*Delta;
e = beta^2 - gamma^2 + 2*gamma - 1;
%% Solve the polynomial numerically.
P = [a b c d e];
R = roots(P);
%% Solve r = cos(2x) for x: x = n*pi +- 1/2 * acos(r). Using n = 0 and 1.
theta = [1/2.*acos(R) -1/2.*acos(R) pi+1/2.*acos(R) pi-1/2.*acos(R)];
figure;
hold on;
x = 0:1/1000:2*pi;
y_1 = sigma*cos(x - theta_s) + sqrt(1 + Delta*cos(2*x));
y_2 = sigma*cos(x - theta_s) - sqrt(1 + Delta*cos(2*x));
plot(x,y_1,'black');
plot(x,y_2,'black');
grid on;
%% Plot theta if real, if positive, if 1st derivative is ~zero, and if 2nd derivative is positive
for j=1:numel(theta);
A = isreal(theta(j));
x_j = theta(j);
y_j = sigma*cos(x_j - theta_s) + sqrt(1 + Delta*cos(2*x_j));
FirstDer = sigma* sin(theta(j) - theta_s) + Delta*sin(2*theta(j))/...
sqrt(1 + Delta*cos(2*theta(j)));
SecDer = -sigma*cos(theta(j)-theta_s) - 2*Delta*cos(2*theta(j))/...
(1 + Delta*cos(2*theta(j)))^(1/2) - Delta^2 * (sin(2*theta(j)))^2/...
(1 + Delta*cos(2*theta(j)))^(3/2);
if A == 1 && x_j>=0 && FirstDer < 1E-7 && SecDer > 0
plot(x_j,y_j,['o','blue'])
end
end
After you finish all plotting, get the axes handle:
ax = gca;
then write:
X = get(ax.Children,{'XData'});
And X will be cell array of all the x-axis values from all lines in the graph. One cell for each line.
For the code above:
X =
[1.961054062875753]
[4.514533853417446]
[1x6284 double]
[1x6284 double]
(First, the code all worked. Thanks for the effort there.)
There are options here. A are couple below
Record the values as you generate them
Within the "success" if statement, simply record the values. See edits to your code below.
This would always be the preferred option for me, it just seems much more efficient.
xyResults = zeros(0,2); %%% INITIALIZE HERE
for j=1:numel(theta);
A = isreal(theta(j));
x_j = theta(j);
y_j = sigma*cos(x_j - theta_s) + sqrt(1 + Delta*cos(2*x_j));
FirstDer = sigma* sin(theta(j) - theta_s) + Delta*sin(2*theta(j))/...
sqrt(1 + Delta*cos(2*theta(j)));
SecDer = -sigma*cos(theta(j)-theta_s) - 2*Delta*cos(2*theta(j))/...
(1 + Delta*cos(2*theta(j)))^(1/2) - Delta^2 * (sin(2*theta(j)))^2/...
(1 + Delta*cos(2*theta(j)))^(3/2);
if A == 1 && x_j>=0 && FirstDer < 1E-7 && SecDer > 0
xyResults(end+1,:) = [x_j y_j]; %%%% RECORD HERE
plot(x_j,y_j,['o','blue'])
end
end
Get the result from the graphics objects
You can get the data you want from the actual graphics objects. This would be the option if there was just no way to capture the data as it was generated.
%First find the objects witht the data you want
% (Ideally you could record handles to the lines as you generated
% them above. But then you could also simply record the answer, so
% let's assume that direct record is not possible.)
% (BTW, 'findobj' is an underused, powerful function.)
h = findobj(0,'Marker','o','Color','b','type','line')
%Then get the `xdata` filed from each
capturedXdata = get(h,'XData');
capturedXdata =
2×1 cell array
[1.96105406287575]
[4.51453385341745]
%Then get the `ydata` filed from each
capturedYdata = get(h,'YData');
capturedYdata =
2×1 cell array
[1.96105406287575]
[4.51453385341745]
I have a general equation
t=tr+(ts-tr)/(1+(a*h)^n)^(1-1/n)
for (h=0, 1, 2, 3), I have t=2.000, 1.6300, 1.2311, 1.1084. therefor there are 4 equations with 4 unknowns tr, ts, a, n
I used "solve" function in matlab
s=solve('tr+(ts-tr)/(1+(a*0)^n)^(1-1/n)=2','tr+(ts-tr)/(1+(a*1)^n)^(1-1/n)=1.63','tr+(ts-tr)/(1+(a*2)^n)^(1-1/n)=1.2311','tr+(ts-tr)/(1+(a*3)^n)^(1-1/n)=1.1084')
and error is
??? Error using ==> mupadmex
Error in MuPAD command: Singularity [ln];
during evaluation of 'numeric::fsolve'
Error in ==> sym.sym>sym.mupadmexnout at 2018
out = mupadmex(fcn,args{:});
Error in ==> solve at 76
[symvars,R] = mupadmexnout('symobj::solvefull',eqns,vars);
What should I do?
The problem appears with you using the solve function. That only works for simple equations, it is better to use the fsolve function. Due to the fact that I am worried that I am doing an assignment for you, I am only going to show you how to do another example using fsolve.
Suppose that you want to solve
1 = x_1
1 = x_1 + x_2
-1 = x_1 + x_2 + x_3
-1 = x_1 + x_2 + x_3 + x_4
then what you firstly need to do is write these as equations equal 0
0 = x_1 - 1
0 = x_1 + x_2 - 1
0 = x_1 + x_2 + x_3 + 1
0 = x_1 + x_2 + x_3 + x_4 + 1
then you need to write a function that takes in a vector x, the components of x will represent x_1, x_2, x_3 and x_4. The output of the function will also be a vector whose components should the outputs of the Right hand side of the above equations (see the function fun below). This function is going to be called by fSolve for it to provide it with guesses of the correct value of x, until it guess correct. When never actually run this function ourselves. That is why it is below the top function.
Then you create a function handle to this function by fHandle = #fun. You can think of fHandle as another name for fun, when we calculate fHandle([1; 2; 3; 4]) this is the same as calculating fun([1; 2; 3; 4]). After this you make an initial guess of the correct vector x, say we chose xGuess = [1; 1; 1; 1]. Finally we pass fHandle and xGuess to fSolve.
Here is the code
function Solve4Eq4Unknown()
fHandle = #fun;
xGuess = ones(4,1);
xSolution = fsolve(fHandle, xGuess)
end
function y = fun(x)
y = zeros(4,1); % This step is not necessary, but it is effecient
y(1) = x(1) - 1;
y(2) = x(1) + x(2) - 1;
y(3) = x(1) + x(2) + x(3) + 1;
y(4) = x(1) + x(2) + x(3) + x(4) + 1;
end
alright well I have the follow function
y=sin(x)^2 + [(10+2x+x^2) / (5+2x^2)]
i need to plot it on the interval y = -2 to y = 2 so how would I set that up?
I did this in matlab
>> y = sin(x).^2 + (10 + 2*x + x.^2)/(5+2*x.^2)
>> x = -2:0.01:2;
is that a correct setup? Or have I done something wrong
You need to declare a variable before you use it. In this case, x doesn't depend on y, so declare it first. In addition, there is a ./ operator missing.
x = -2:0.01:2;
y=sin(x).^2 + (10+2*x+x.^2) ./ (5+2*x.^2);
plot(x,y)
f = #(x) sin(x)^2 + [(10+2*x+x^2) / (5+2*x^2)];
ezplot(f)