square of a vector

I have to calculate a square of vector which should results a scalar value. i.e) A=(B-C)^2 B and C are vectors and I need A as a scalar. How can I implement this in matlab??

 採用された回答

Honglei Chen
Honglei Chen 2012 年 10 月 31 日
編集済み: Honglei Chen 2012 年 10 月 31 日

0 投票

My guess is you need an inner product, i.e. A = |B-C|^2, you can do it many different ways, one way is
B = ones(3,1);
C = ones(3,1);
A = (B-C)'*(B-C)

6 件のコメント

Berbia
Berbia 2012 年 10 月 31 日
I got it...Can I use dot(B,C)? Is both are same?
Honglei Chen
Honglei Chen 2012 年 10 月 31 日
編集済み: Honglei Chen 2012 年 10 月 31 日
yes they are the same, but you should use
dot(B-C,B-C)
Matt J
Matt J 2012 年 10 月 31 日
No. You could do dot(B-C,B-C) or, more efficiently
tmp=B-C;
A=dot(tmp,tmp);
The DOT command is relatively slow, though, in case that matters.
Berbia
Berbia 2012 年 10 月 31 日
Thanks a lot...I have to do this operation repeatedly in loop. which is more efficient, whether tmp=B-C; dot(tmp,tmp); or norm(B-C)^2?
Honglei Chen
Honglei Chen 2012 年 10 月 31 日
I'd say
temp = B-C;
temp'*temp
Matt J
Matt J 2012 年 10 月 31 日
編集済み: Matt J 2012 年 10 月 31 日
You should think about whether the loop can be avoided altogether, since this sounds like a very vectorizable operation. If B and C are matrices and you want the dot product along columns, for example
temp=B-C;
result = sum(temp.^2,1);

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

その他の回答 (1 件)

Matt J
Matt J 2012 年 10 月 31 日

1 投票

A=norm(B-C)^2;

カテゴリ

ヘルプ センター および File ExchangeMATLAB Coder についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by