variable in solving the equation - matlab

I want to solve equations in matlab, eg.
100+a/2=173*cos(b)
sqrt(3)*a/2=173*sin(b)
and the code would be:
[a,b]=solve('100+a/2=173*cos(b)','sqrt(3)*a/2=173*sin(b)','a','b')
However, if I want to take 100 as a variable, like
for k=1:100
[a,b]=solve('k+a/2=173*cos(b)','sqrt(3)*a/2=173*sin(b)','a','b')
end
There would be an error, how to make it?
degree=140/1000000;
p=42164000;
a=6378136.5;
b=6356751.8;
x_1=0;
y_1=p;
z_1=0;
for i=451:550
for j=451:550
alpha=(1145-i)*degree;
beta=(1145-j)*degree;
x_2=p/cos(alpha)*tan(beta);
y_2=0;
z_2=p*tan(alpha);
syms x y z x_1 x_2 y_1 y_2 z_1 z_2 a b
eq = [(x-x_1)*(y2-y_1)-(x_2-x_1)*(y-y_1),(x-x_1)*(z_2-z_1)-(x_2-x_1)*(z-z_1), b^2*(x^2+y^2)+a^2*(y^2)-a^2*b^2 ];
sol = solve(eq(1),x,eq(2),y, eq(3),z);
sol.x
sol.y
sol.z
end
end
I got the expression value, how do I get the numeric value of x,y,z?
[['x(1)=';'x(2)='],num2str(double(sol.x))]
not work ,shows
??? Error using ==> mupadmex
Error in MuPAD command: DOUBLE cannot convert the input expression into a double array.
If the input expression contains a symbolic variable, use the VPA function instead.
Error in ==> sym.sym>sym.double at 927
Xstr = mupadmex('mllib::double', S.s, 0);
Error in ==> f2 at 38
[['x(1)=';'x(2)='],num2str(double(sol.x))]

If you have access to the Symbolic Toolkit then you do the following:
syms a b k
eq = [k+a/2-173*cos(b), sqrt(3)*a/2-173*sin(b)];
sol = solve(eq(1),a,eq(2),b);
sol.a = simplify(sol.a);
sol.b = simplify(sol.b);
% There are two solutions for 'a' and 'b'
% check residuals for example k=20
subs(subs(eq,{a,b},{sol.a(1),sol.b(1)}),k,20)
% ans = 0.2e-13
subs(subs(eq,{a,b},{sol.a(2),sol.b(2)}),k,20)
% ans = 0.2e-13
Edit 1
Based on new code by OP the matlab script to solve this is:
clear all
clc
syms alpha beta
degree=140/1000000;
p=42164000;
a=6378136.5;
b=6356751.8;
x_1=0;
y_1=p;
z_1=0;
x_2 = p/cos(alpha)*tan(beta);
y_2 = 0;
z_2 = p*tan(alpha);
syms x y z
eq = [(x-x_1)*(y_2-y_1)-(x_2-x_1)*(y-y_1);...
(x-x_1)*(z_2-z_1)-(x_2-x_1)*(z-z_1); ...
b^2*(x^2+y^2)+a^2*(y^2)-a^2*b^2 ];
sol = solve(eq(1),x,eq(2),y,eq(3),z);
sol.x = simplify(sol.x);
sol.y = simplify(sol.y);
sol.z = simplify(sol.z);
pt_1 = [sol.x(1);sol.y(1);sol.z(1)] % First Solution Point
pt_2 = [sol.x(2);sol.y(2);sol.z(2)] % Second Solution Point
x = zeros(100,100);
y = zeros(100,100);
z = zeros(100,100);
for i=451:550
disp(['i=',num2str(i)])
for j=451:550
res = double(subs(pt_1,{alpha,beta},{(1145-i)*degree,(1145-j)*degree}));
x(i-450, j-450) = res(1);
y(i-450, j-450) = res(2);
z(i-450, j-450) = res(3);
end
end
disp('x=');
disp(x);
disp('y=');
disp(x);
disp('z=');
disp(x);

I would try
for i=1:100
k=num2str(i)
[a,b]=solve('100+a/2=173*cos(b)','sqrt(3)*a/2=173*sin(b)','a','b')
end
and then solve the equation

Related

Find roots using fsolve

Basically I would like to use the fsolve command in order to find the roots of an equation.
I think I should create a function handle that evaluates this equation in the form "right hand side - left hand side =0", but I've been struggling to make this work. Does anyone know how to do this?
The equation itself is 1/sqrt(f) = -1.74log((1.254/((1.27310^8)sqrt(f)))+((110^-3)/3.708)). So I would like to find the point of intersection of the left and right side by solving for 1/sqrt(f)+(1.74log((1.254/((1.27310^8)sqrt(f)))+((110^-3)/3.708))) = 0 using fsolve.
Thanks a lot!
The code so far (not working at all)
f = #(x) friction(x,rho,mu,e,D,Q, tol, maxIter) ;
xguess = [0, 1];
sol = fsolve(x, xguess ) ;
function y = friction(x,rho,mu,e,D,Q, tol, maxIter)
D = 0.1;
L = 100
rho = 1000;
mu = 0.001;
e = 0.0001;
Q = 0.01;
U = (4*Q)/(pi*D^2);
Re = (rho*U*D)/mu ;
y = (1/sqrt(x))-(-1.74*log((1.254/(Re*sqrt(x)))+((e/D)/3.708)))
end
Error message:
Error using lsqfcnchk (line 80)
FUN must be a function, a valid character vector expression, or an inline function object.
Error in fsolve (line 238)
funfcn = lsqfcnchk(FUN,'fsolve',length(varargin),funValCheck,gradflag);
Error in Untitled (line 6)
sol = fsolve(x, xguess ) ;
opt = optimset('Display', 'Iter');
sol = fsolve(#(x) friction(x), 1, opt);
function y = friction(x)
D = 0.1;
L = 100; % note -- unused
rho = 1000;
mu = 0.001;
e = 0.0001;
Q = 0.01;
U = (4*Q)/(pi*D^2);
Re = (rho*U*D)/mu ;
y = (1/sqrt(x))-(-1.74*log((1.254/(Re*sqrt(x)))+((e/D)/3.708)));
end
sol = 0.0054
the first argument of fsolve should be the function not variable. Replace:
sol = fsolve(x, xguess );
with
sol = fsolve(f, xguess );
And define Rho, mu, e etc before you define f (not inside the friction function).

Issue with storing error at each iteration on Matlab - "unrecognized variable"

I've written a modified Newton's method code, and I'm looking to plot the error at each iteration vs the iteration, but after my code runs Matlab does not recognize my error function or the iterations.
function[x,k,e] = mynewton(x0,tol)
f = #(x) (x-1).^5*exp(x);
df = #(x) 5*(x-1).^4*exp(x)+(x-1).^5*exp(x);
kMax = 200;
format long
x=x0;
y=f(x);
e = [];
k = 0;
disp(' k x error')
while abs(y) > tol && k < kMax
k=k+1;
x = x - f(x)/df(x);
y = f(x);
e_k = abs(x-1);
e(k) = e_k;
disp([k x e_k])
end
end
The output will be 3 columns showing k, x, and e_k at each step, but it won't store these values properly into a vector. Instead, it shows
>> k
Unrecognized function or variable 'k'.
What am I doing wrong?
Any suggestions are very appreciated!!
You need to call your function as:
[x, k, e] = mynewton( x0, tol);
After this call, you can enter k at command window and see its value.

extended algorithm implementation in matlab

i have found following pseudo-code for extended euclidean algorithm
i implemented following algorithm
function [x1,y1,d1]=extend_eucledian(a,b)
if b==0
x1=1;
y1=0;
d1=a;
return;
end
[x1,y1,d1]=extend_eucledian(b,mod(a,b));
x1=y1;
y1=x1-floor(a/b)*y1;
d1=d1;
end
when i run following this program, i got following result
[x1,y1,d1]=extend_eucledian(23,20)
x1 =
0
y1 =
0
d1 =
1
i guess that [x1,y1,d1] are not changing their values during the iteration, for instance , i have tried following code
function [x1,y1,d1]=extend_eucledian(a,b)
if b==0
x1=1;
y1=0;
d1=a;
return;
else
x1=y1;
y1=x1-floor(a/b)*y1;
d1=d1;
end
[x1,y1,d1]=extend_eucledian(b,mod(a,b));
end
but i got
>> [x1,y1,d1]=extend_eucledian(23,20)
Undefined function or variable 'y1'.
Error in extend_eucledian (line 8)
x1=y1;
how can i fix this problem? where i am making mistake?
The problem can be solved by introducing intermediate working variables, that will store the result of the recursive call:
function [x,y,d]=extended_euclid(a,b)
if b==0
x=1;
y=0;
d=a;
return;
end
[x1,y1,d1]=extended_euclid(b,mod(a,b));
x=y1;
y=x1-floor(a/b)*y1;
d=d1;
end
This function works as expected:
>> [x, y, d] = extended_euclid(23,20)
x =
7
y =
-8
d =
1
>> [x, y, d] = extended_euclid(25,20)
x =
1
y =
-1
d =
5
The error in the question is that x1, y1, d1 are used simultaneously as working and output variables. The code can be rewritten using a new tern [x, y d] for the output values:
function [x y d]=eucledian_pairs(a,b)
%a>0,b>0
%d=gcd(a,b) a*x+y*b=d
[x1,y1,d1]=extend_eucledian(a,b);
x=y1;
y=x1-floor(a/b)*y1;
d=d1;
function [x1,y1,d1]=extend_eucledian(a,b)
if b==0
x1=1;
y1=0;
d1=a;
return;
end
[x1,y1,d1]=extend_eucledian(b,mod(a,b));
end
end
Executing this code gives the desired result.
>> [x y d]=eucledian_pairs(20,25)
x =
0
y =
1
d =
5

Matlab Differential Equations Euler’s method

I need help plotting a differential equation ... it keeps coming out all funky and the graph is not what it's supposed to look like.
function [dydt] = diff(y,t)
dydt = (-3*y)+(t*(exp(-3*t)));
end
tI = 0;
yI = -0.1;
tEnd = 5;
dt = 0.5;
t = tI:dt:tEnd;
y = zeros(size(t));
y(1) = yI;
for k = 2:numel(y)
yPrime = diff(t(k-1),y(k-1));
y(k) = y(k-1) + dt*yPrime;
end
plot(t,y)
grid on
title('Engr')
xlabel('Time')
ylabel('y(t)')
legend(['dt = ' num2str(dt)])
That's my code, but the graph is not anything like what it's supposed to look like. Am I missing something like an index for the for statement?
Edit
I am getting an error:
Error using diff
Difference order N must be a positive integer scalar.
Error in diff3 (line 12)
yPrime = diff(t(k-1),y(k-1));
After fixing the errors pointed out by Danil Asotsky and horchler in the comments:
avoiding name conflict with built-in function 'diff'
changing the order of arguments to t,y.
decreasing the time-step dt to 0.1
converting ODE right-hand side to an anonymous function
(and removing unnecessary parentheses in the function definition), your code could look like this:
F = #(t,y) -3*y+t*exp(-3*t);
tI = 0;
yI = -0.1;
tEnd = 5;
dt = 0.1;
t = tI:dt:tEnd;
y = zeros(size(t));
y(1) = yI;
for k = 2:numel(y)
yPrime = F(t(k-1),y(k-1));
y(k) = y(k-1) + dt*yPrime;
end
plot(t,y)
grid on
title('Engr')
xlabel('Time')
ylabel('y(t)')
legend(['dt = ' num2str(dt)])
which performs as expected:

How to call automatically symbolic variables in a loop in Matlab

Is there anyway to use a loop index to call symbolic variables in Matlab? For example, consider the following code whose goal is to store the symbolic expression "x1+x2+x3" in "y".
syms x1 x2 x3
y = 0;
for i = 1:3
y = y + xi;
end
The code does not work because on each iteration Matlab reads "y = y + xi" and returns the error "xi is undefined", instead of reading "y = y + x1", "y = y + x2" and "y = y + x3", is there anyway around this?
Thanks.
I'd suggest this, provided that you can create your numbered symbolic variable slightly differently:
x = sym('x',[1 3]); % or: syms x1 x2 x3; x = [x1 x2 x3];
y = x(1);
for i = 2:numel(x)
y = y+x(i);
end
Of course in this simple example, the entire for loop and everything else can be replaced with:
y = sum(sym('x',[1 3]));
See the documentation on sym for more details.
EDIT: Note that, as #pm89 points out, by allocating the 1-by-3 symbolic vector x, you of course won't have direct access to the symbolic variables x1,x2, and x3 in your workspace, but will have to index them as shown. This is similar to working with arrays or cells and has many of the same benefits as my second vectorized example illustrates.
If your Matlab does not support the matrix declaration of symbolics directly (as sym('x',[3 1])) you can write your own function for that:
function out = Matrix_Sym(name, size) %#ok<STOUT>
rows = size(1);
cols = size(2);
S = '';
for k1 = 1:rows
for k2 = 1:cols
if rows == 1
S = [S name int2str(k2) ' '];
elseif cols == 1
S = [S name int2str(k1) ' '];
else
S = [S name int2str(k1) int2str(k2) ' '];
end
end
end
eval(['syms ' S]);
eval (['out = reshape([' S '], [rows, cols]);']);
Then you could get the same result with:
x = Matrix_Sym('x', [3 1])
...