Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to normalize a vector in MATLAB efficiently? Any related built-in function? [closed]

I normalize a vector V in MATLAB as following:

normalized_V = V/norm(V); 

however, is it the most elegant (efficient) way to normalize a vector in MATLAB?

like image 398
Kamran Bigdely Avatar asked Jun 30 '09 00:06

Kamran Bigdely


People also ask

How do you normalize a vector function?

To normalize a vector, therefore, is to take a vector of any length and, keeping it pointing in the same direction, change its length to 1, turning it into what is called a unit vector. Since it describes a vector's direction without regard to its length, it's useful to have the unit vector readily accessible.

Can you normalize a vector?

When we normalize a vector, we actually calculate V/|V| = (x/|V|, y/|V|, z/|V|) . Hence, we can call normalized vectors as unit vectors (i.e. vectors with unit length). Any vector, when normalized, only changes its magnitude, not its direction.


1 Answers

The original code you suggest is the best way.

Matlab is extremely good at vectorized operations such as this, at least for large vectors.

The built-in norm function is very fast. Here are some timing results:

V = rand(10000000,1); % Run once tic; V1=V/norm(V); toc           % result:  0.228273s tic; V2=V/sqrt(sum(V.*V)); toc   % result:  0.325161s tic; V1=V/norm(V); toc           % result:  0.218892s 

V1 is calculated a second time here just to make sure there are no important cache penalties on the first call.

Timing information here was produced with R2008a x64 on Windows.


EDIT:

Revised answer based on gnovice's suggestions (see comments). Matrix math (barely) wins:

clc; clear all; V = rand(1024*1024*32,1); N = 10; tic; for i=1:N, V1 = V/norm(V);         end; toc % 6.3 s tic; for i=1:N, V2 = V/sqrt(sum(V.*V)); end; toc % 9.3 s tic; for i=1:N, V3 = V/sqrt(V'*V);      end; toc % 6.2 s *** tic; for i=1:N, V4 = V/sqrt(sum(V.^2)); end; toc % 9.2 s tic; for i=1:N, V1=V/norm(V);           end; toc % 6.4 s 

IMHO, the difference between "norm(V)" and "sqrt(V'*V)" is small enough that for most programs, it's best to go with the one that's more clear. To me, "norm(V)" is clearer and easier to read, but "sqrt(V'*V)" is still idiomatic in Matlab.

like image 140
Mr Fooz Avatar answered Sep 19 '22 13:09

Mr Fooz