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

Thread Subject:
Built a matrix z(3x2) avoiding loops

Subject: Built a matrix z(3x2) avoiding loops

From: Jose

Date: 24 Mar, 2009 01:45:13

Message: 1 of 2

Hi everyone, please I need help:

I have the next code:

nrp=3;
nrv=2;

x=rand(nrp,:) % 2D- dimensional data
a=rand(nrv,:) % 2D- dimensional parameter

inversa=2x2 matrix [ 1 2; 3 4]

How I can built a matrix z (3x2) avoiding loops as:

(x(1,:)-a(1,:))*inversa*(x(1,:)-a(1,:))' (x(1,:)-a(2,:))*inversa*(x(1,:)-a(2,:))'

(x(2,:)-a(1,:))*inversa*(x(2,:)-a(1,:))' (x(2,:)-a(2,:))*inversa*(x(2,:)-a(2,:))'

(x(3,:)-a(1,:))*inversa*(x(3,:)-a(1,:))' (x(3,:)-a(2,:))*inversa*(x(3,:)-a(2,:))'

Thanks in advance,

Jose.

Subject: Built a matrix z(3x2) avoiding loops

From: Roger Stafford

Date: 24 Mar, 2009 19:51:01

Message: 2 of 2

"Jose " <jose.l.vega@gmail.com> wrote in message <gq9dv9$rrt$1@fred.mathworks.com>...
> Hi everyone, please I need help:
> I have the next code:
>
> nrp=3;
> nrv=2;
>
> x=rand(nrp,:) % 2D- dimensional data
> a=rand(nrv,:) % 2D- dimensional parameter
>
> inversa=2x2 matrix [ 1 2; 3 4]
>
> How I can built a matrix z (3x2) avoiding loops as:
>
> (x(1,:)-a(1,:))*inversa*(x(1,:)-a(1,:))' (x(1,:)-a(2,:))*inversa*(x(1,:)-a(2,:))'
> (x(2,:)-a(1,:))*inversa*(x(2,:)-a(1,:))' (x(2,:)-a(2,:))*inversa*(x(2,:)-a(2,:))'
> (x(3,:)-a(1,:))*inversa*(x(3,:)-a(1,:))' (x(3,:)-a(2,:))*inversa*(x(3,:)-a(2,:))'
>
> Thanks in advance,
> Jose.

  The following avoids for-loops, Jose, but with all the "repmatting" and reshaping, I am not sure it is any faster. Try it and see. I have generalized it to a matrix 'x' of size nrp by n, a matrix 'a' of size nrv by n, and a matrix 'inversa' of size n by n.

 z = repmat(x,nrv,1)-reshape(repmat(reshape(a,1,[]),nrp,1),[],n);
 z = reshape(sum(((z*inversa).*z),2),nrp,nrv);

Roger Stafford

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us