Vector function is only returning a scalar output

조회 수: 10 (최근 30일)
Adam Vanek
Adam Vanek 2017년 10월 3일
댓글: Adam Vanek 2017년 10월 3일
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