Vector Add Example

Why use a programming language like MATLAB?

(you answer this)

Let us say for some reason we want a program that would add any three planar vectors together giving us the resultant vector's magnitude and direction.

%
% Function add three planar vectors
% Syntax: [result_force,result_angle]=forceadd(f1,theta1,f2,theta2,f3,theta3)
% Author: Scott D. Johnson as an example to understanding MATLAB/octave
%function[f4,theta4]=forceadd(f1,theta1,f2,theta2,f3,theta3)
%
% sind,cosd,tand are matlab shortcuts...for octave you have to convert
% or make simple programs to do those funtions.
%
f1x = f1*cosd(theta1);
f1y = f1*sind(theta1);
f2x = f2*cosd(theta2);
f2y = f2*sind(theta2);
f3x = f3*cosd(theta3);
f3y = f3*sind(theta3);
fx = f1x+f2x+f3x;
fy = f1y+f2y+f3y;
f4 = sqrt(fx*fx+fy*fy);
%
% Should use atan2, not atan.
%
%theta4 = atand(fy/fx);
%
theta4 = atan2d(fy,fx);
end

This can be extended even further as follows:

% Function add n planar vectors
% Syntax: [result_force,result_angle]=forceadd(f1,theta1,...)
% Purpose: Too add planar vectors for a class demonstration
% Explanation: Uses Pythagoreans theorem to get the magnitude of the resulting
% force and trigonometry to get the resulting angle
% Calling sequence example: [force,theta] = forceadd(5,30,6,20,4,60)
% Inputs: f1, theta1,... are the magnitude and the angle of the different vectors
% Output: result_force, result_angle is the magnitude of the added vectors with
% their directions as defined by an angle from the reference
% direction (x)
% Dependencies: sqrt,atand2d
% Notes: Extends the first class example to allow for a variable number of
% arguments
% Author: Scott D. Johnson as an example to understanding MATLAB/octave 2006
% Revisions: SDJ minor revisions 3/2008
%
function[f,theta]=forceaddmulti(varargin)
%
% sind,cosd,tand are matlab shortcuts...for octave you have to convert
% or make simple programs to do those funtions.
%
fxtot = 0;
fytot = 0;
%
% Varargin uses the "cell" structure...
% To extract pieces of a cell use {} instead of ()
%
for k=1:2:length(varargin)-1
fx = varargin{k}*cosd(varargin{k+1});
fy = varargin{k}*sind(varargin{k+1});
fxtot = fxtot + fx;
fytot = fytot + fy;
end
f = sqrt(fxtot*fxtot+fytot*fytot);
%
% Should use atan2, not atan.
%
%theta = atand(fytot/fxtot);
%
theta = atan2d(fytot,fxtot);
end