-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnormalize.m
70 lines (57 loc) · 1.7 KB
/
normalize.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
function [v, v_mag] = normalize(v)
% NORMALIZE Safe normalization of the columns of the input matrix
%
% Safely normalize the columns of the input vectors. When the magnitude is
% exactly 0, the output vector will be [1; 0; 0]. This function can also
% output the magnitude of each vector, as a useful byproduct.
%
% [v, v_mag] = NORMALIZE(v)
%
% Inputs:
%
% v Vector(s) (3-by-n)
%
%
% Outputs:
%
% v Unit vector(s) (3-by-n)
% v_mag Magnitudes (2-norm) of each of the vectors
% Copyright 2016 An Uncommon Lab
%#codegen
% If running in regular MATLAB, vectorize.
if isempty(coder.target)
v_mag = vmag(v);
valid = v_mag > 0;
v(1, ~valid) = 1;
v(2:end, ~valid) = 0;
if any(valid)
v(:, valid) = bsxfun(@times, v(:,valid), 1./v_mag(valid));
end
% Otherwise, when running in some type of embedded code, use efficient
% (non-vectorized) code.
else
% If we need each v_mag...
if nargout >= 2
v_mag = vmag(v);
for k = 1:size(v, 2)
if v_mag(k) == 0
v(1,k) = 1;
v(2:end,k) = 0;
else
v(:,k) = v(:,k) ./ v_mag(k);
end
end
% Otherwise, v_mag is disposible, so just use a scalar.
else
for k = 1:size(v, 2)
v_mag = vmag(v(:,k));
if v_mag == 0
v(1,k) = 1;
v(2:end,k) = 0;
else
v(:,k) = v(:,k) ./ v_mag;
end
end
end
end
end % normalize