Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

New to MATLAB?

square of a vector

Asked by Berbia

Berbia (view profile)

on 31 Oct 2012

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??

0 Comments

Berbia

Berbia (view profile)

Products

No products are associated with this question.

2 Answers

Answer by Honglei Chen

Honglei Chen (view profile)

on 31 Oct 2012
Edited by Honglei Chen

Honglei Chen (view profile)

on 31 Oct 2012
Accepted answer

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 Comments

Berbia

Berbia (view profile)

on 31 Oct 2012

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 (view profile)

on 31 Oct 2012

I'd say

temp = B-C;
temp'*temp
Matt J

Matt J (view profile)

on 31 Oct 2012

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);
Honglei Chen

Honglei Chen (view profile)

Answer by Matt J

Matt J (view profile)

on 31 Oct 2012
 A=norm(B-C)^2;

0 Comments

Matt J

Matt J (view profile)

Contact us