Vector function is only returning a scalar output
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Adam Vanek
am 3 Okt. 2017
Kommentiert: Adam Vanek
am 3 Okt. 2017
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 Kommentare
Matt J
am 3 Okt. 2017
That is not sufficient for a no-error condition. If a=b=c=ones(N,1) an error would occur.
Akzeptierte Antwort
Matt J
am 3 Okt. 2017
Bearbeitet: Matt J
am 3 Okt. 2017
function Roots = Quadratic( a, b, c, plusOrMinus )
Roots = (-b + plusOrMinus.*sqrt( (b .^2 - 4.* a.* c) ) ) ./ (2 .* a);
Roots(imag(Roots)~=0)=nan;
3 Kommentare
Matt J
am 3 Okt. 2017
Bearbeitet: Matt J
am 3 Okt. 2017
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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Problem-Based Optimization Setup finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!