norm calculation using for loop

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?

 採用された回答

Adam
Adam 2016 年 8 月 12 日

1 投票

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 件のコメント

g.p
g.p 2016 年 8 月 12 日
編集済み: g.p 2016 年 8 月 12 日
thanks adam , but i have to perform it element-wise using for loop ,and without for loop and need to justify which is fast.
Adam
Adam 2016 年 8 月 12 日
If you have to perform it with a loop then I assume it is homework which you should be able to work out yourself from the 2nd version I gave above.
Converting this into a loop just uses the basics of Matlab:
n = sqrt( sum( x.^2 ) );
Aash
Aash 2017 年 10 月 16 日
did u calculate it using for loops? how?
KL
KL 2017 年 10 月 16 日
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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

g.p
2016 年 8 月 12 日

コメント済み:

KL
2017 年 10 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by