Clear Filters
Clear Filters

norm calculation using for loop

3 views (last 30 days)
g.p
g.p on 12 Aug 2016
Commented: KL on 16 Oct 2017
hello , can anybody tell me how to calculate l2 norm of x=[2 3 -5 3 1] using for loop and without loop, and which one is efficient and fast?

Accepted Answer

Adam
Adam on 12 Aug 2016
n = norm( x );
does it without a loop. There is no reason to do it with a loop. Even if you don't use norm you would still vectorise is as:
n = sqrt( sum( x.^2 ) );
If you really want a loop the derivation is not difficult though. The vectorised version should certainly be faster, but you can test this yourself.
  4 Comments
Aash
Aash on 16 Oct 2017
did u calculate it using for loops? how?
KL
KL on 16 Oct 2017
As Adam has mentioned in his answer, loop is not necessary but if it's a homework and you must use a loop, then read the documentation to know how it works and then use the for loop iterator to index through the vector.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!