How to use two outputs from function in another functions calculation
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I need to figure out the angle between two vectors using functions. I Have figured out the dot product and the length of the vectors in two separate functions, and now bringing them together I can't seem to use both of the results from the length function as it only takes the one result. I am really new to MATLAB and pretty much have little idea what I'm doing, any help is greatly appreciated!
Here is the dot product code:
function c = myScalProd(a,b)
% This Matlab function calculates the scalar
% product of two vectors, a and b.
% Call syntax: y = myScalProd(a,b) or myScalProd(a,b)
% Input: two vectors of equal length, a and b
a= [2 4 1];
b=[-2 3 -2];
% Output: c, the value of the scalar product of a and b
n = length(a); % Get the length of the vector a
c=0; % Initialise the variable c
for i=1:n
c = c + a(i)*b(i);
end
disp(['Scalar Product : ', num2str(c)])
end
and then the length code:
function [d,g,w] = myLengthCalc()
a=[2 4 1];
b=[-2 3 -2];
c=[4 1 6 2 3];
d=(sqrt(sum(a.^2)));
%displays the values for a
disp(['Length of Vector a: ', num2str(d)])
g=(sqrt(sum(b.^2)));
disp(['Length of Vector b: ', num2str(g)])
w=(sqrt(sum(c.^2)));
disp(['Length of Vector c: ', num2str(w)])
end
Then Finally the part I am stuck with:
function thetaInDegrees = myAngleFind()
theta = myScalProd/myLengthCalc%;
thetaInDegrees= acosd(theta);
disp(['Angle Between: ', num2str(thetaInDegrees)])
end
0 Kommentare
Antworten (1)
Jan
am 22 Feb. 2018
I omit the unnecessary code (even the valuable comments - for clarity, leave them in the real code):
function c = myScalProd(a,b)
n = length(a);
c = 0; % Initialise the variable c
for i = 1:n
c = c + a(i)*b(i);
end
end
function d = myLengthCalc(a)
d = sqrt(sum(a.^2));
end
function main
a = [2 4 1];
b = [-2 3 -2];
theta = myScalProd(a, b) / (myLengthCalc(a) * myLengthCalc(b))
thetaInDegrees = acosd(theta)
end
Now mxScalProd(a,b) gets the two variables as inputs. myLengthCalc(x) replies the Euclidean norm of the input vector.
By the way: acos is numerically instable: The rounding error gets huge for certain angles. asin has the same problem for other angles. So better use:
theta = atan2d(norm(cross(a,b)), dot(a,b))
0 Kommentare
Siehe auch
Kategorien
Mehr zu Structures 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!