Vector function is only returning a scalar output

7 次查看(过去 30 天)
I have the function:
function [ theta4 ] = ThetaFour( L, theta2 )
%given equations, finding polynomials for the quad formula
k1 = (L(1)/L(2));
k2 = (L(1)/L(4));
k3 = ((L(1)^2) + (L(2)^2) - (L(3)^2) + (L(4))^2) / (2*L(2)*L(4));
a = cosd(theta2) - k1 -k2*cosd(theta2) + k3;
b = -2*sind(theta2);
c = k1 - (k2 + 1) * cosd(theta2) + k3;
%finding final angle using the quadratic function function created for
%projectile motion script
theta4 = 2*atand(Quadratic(a,b,c,-1))
end
  • L is a vector [0.1313, 0.0475, 0.0880, 0.0960]
  • theta 2 is a vector [0:90]
During this process: a, b, and c all become vectors of length 90
My Quadratic function is:
function Roots = Quadratic( a, b, c, plusOrMinus )
%Uses the quadratic formula to solve for roots
if ((b .^ 2)-(4 .* a .* c) >= 0)
if (plusOrMinus == 1)
Roots = (-b + sqrt( (b .^2 - 4.* a.* c) ) ) / (2 .* a);
else
Roots = (-b - sqrt( (b .^2 - 4.* a.* c) ) ) / (2 .* a);
end
else
error('Coefficiants yield a complex root. b^2 - 4ac must be 0 or greater.')
end
a, b, c should be going in as vectors, while plusOrMinus is -1, returning a vector
Changing a, b, or c to a scalar produces a vector, but all three as vectors produces a scalar.
For example, Quadratic(-.5, b, c, -1) returns a full vector as does Quadratic(a, 10, c, -1) while Quadratic(a, b, c, -1) is just returning one value.
I would like to know how to get Quadratic(a, b, c, -1) to return a vector. Thank you in advance.
  3 个评论
Adam Vanek
Adam Vanek 2017-10-3
That is correct. In the case above, a,b,c are all positive numbers, so no error message occurs.
Matt J
Matt J 2017-10-3
That is not sufficient for a no-error condition. If a=b=c=ones(N,1) an error would occur.

请先登录,再进行评论。

采纳的回答

Matt J
Matt J 2017-10-3
编辑:Matt J 2017-10-3
function Roots = Quadratic( a, b, c, plusOrMinus )
Roots = (-b + plusOrMinus.*sqrt( (b .^2 - 4.* a.* c) ) ) ./ (2 .* a);
Roots(imag(Roots)~=0)=nan;
  3 个评论
Matt J
Matt J 2017-10-3
编辑:Matt J 2017-10-3
The problem is all down to the if.
No, the reason that a scalar was returned is that the element-wise division operator './' was not being used. Although, I do wonder if the OP really wants a vector argument to if, see see my Comment above.
Adam Vanek
Adam Vanek 2017-10-3
Thank you Matt, I am glad you both answered my question as well as expounded upon the arguments in my if statement.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Problem-Based Optimization Setup 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by