Error with equation using sym/subsindex
古いコメントを表示
When I try to run my code, I get "Error using sym/subsindex...Invalid indexing or function definition..." and "Error in line with f(A) = x.*tan(A)-(g./(2.*V.^2.*((cos(A)).^2))).* x.^2-y". Can someone please show me how I can fix my code below?
% Variables
V = 1500;
g = 32.2;
x = 500;
y = 50;
tol = 0.000001; % Error tolerance
% Function
syms A
f(A) = x.*tan(A)-(g./(2.*V.^2.*((cos(A)).^2))).* x.^2-y;
x_coor = linspace(0, 0.2, 1000);
y_coor = f(x_coor);
figure
plot(x_coor, y_val)
xline(0.103247833251953)
yline(0)
root = bisection(f,0.1,0.2,tol); % Root from Bisection Method
function [c] = bisection(f,a,b,tol) % Function file
% Inputs: f = function; a,b = range or interval for roots to be found where a>b; tol = error tolerance
err = 1/tol;
% Bisection method
while err>tol
c = (a+b)/2;
if(abs(f(c))== 0) %if f(c) is equal to 0, then stop
break
end
if f(a)*f(c)<0
b=c;
else
a=c;
end
err=abs(a-b);
end
end
採用された回答
その他の回答 (1 件)
Sulaymon Eshkabilov
2021 年 4 月 6 日
In your code, there are a few confusions and flaws. You've define: f(A) = x.*tan(A)-(g./(2.*V.^2.*((cos(A)).^2))).* x.^2-y; f as a function of A. At the same time, y_coor = f(x_coor). The syntax of y_coor = f(x_coor) is not correct as defined above.
Some confusions need to be fixed, y_coor vs. y_val, x vs. x_coor.
Moreover, without the value of A, y_coor can't be computed.
Here is a corrected code:
% Variables
V = 1500;
g = 32.2;
x = 500;
y = 50;
tol = 0.000001; % Error tolerance
% Function
syms A
f(A)= x.*tan(A)-(g./(2.*V.^2.*((cos(A)).^2))).* x.^2-y;
root = bisection(f,0.1,0.2,tol); % Root from Bisection Method
A = root;
fprintf('Computed root is: %f \n ', root);
% Plot:
x = linspace(0, 0.2, 1000);
Y = @(x)(x.*tan(A)-(g./(2.*V.^2.*((cos(A)).^2))).* x.^2-y);
y_val=Y(x);
figure
plot(x, y_val)
xline(0.103247833251953)
yline(0)
function [c] = bisection(f,a,b,tol) % Function file
% Inputs: f = function; a,b = range or interval for roots to be found where a>b; tol = error tolerance
err = 1/tol;
% Bisection method
while err>tol
c = (a+b)/2;
if(abs(f(c))== 0) %if f(c) is equal to 0, then stop
break
end
if f(a)*f(c)<0
b=c;
else
a=c;
end
err=abs(a-b);
end
end
2 件のコメント
emma
2021 年 4 月 6 日
Walter Roberson
2021 年 4 月 6 日
The syntax of y_coor = f(x_coor) is not correct as defined above.
That is not correct. The poster defined a symbolic function. Just like regular functions and anonymous functions, the named parameters will be substituted with whatever is passed to the function when it is invoked, so it is fine for numeric values or a variable of a different name to be passed to f.
Perhaps the user edited the original code after you posted, but for the code currently posted at least, there are almost no changes needed to get the plot -- only one misnamed variable.
カテゴリ
ヘルプ センター および File Exchange で Assumptions についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

