15 views (last 30 days)

Hello all, I am using following code to estimate pairwise angle between for a vector. Where the angle should be between 0 to 2*pi. I am able to predict the angle. But I need your advise on implementing this two for loops. This is slowing the code. Looking forward for your attention. In the code, XYdata is a n x 2 matrix representing the Cartesian coordinates of individual point [xi, yi]. I presume this slow is because of two FOR loops.

for i2 =1:length(XYdata_new)

for j2 = 1:length(XYdata_new)

angle_ij(i2,j2)= Angle360(XYdata_new(i2,1), XYdata_new(i2,2), XYdata_new(j2,1),XYdata_new(j2,2));

end

end

Thanks in advance.

Star Strider
on 19 Feb 2016

Star Strider
on 19 Feb 2016

In the matrix bsxfun calculates, the first row are the angle differences between the first angle an all the others (so ‘AngleDifferences(1,2)’ is ‘Angles360(1)-Angles360(2)’ and so for the rest. This is the angular equivalent of the pdist function.

If you have two different sets of angles, run ‘Angles’ and ‘Angles360’ on each set separately, producing for example ‘Angles360A’ and ‘Angles360B’. The bsxfun call then becomes:

AngleDifferences = bsxfun(@minus, Angles360A(:), Angles360B(:)'); % Pairwise Angle Differences

The ‘AngleDifferences(1,2)’ matrix element would then become for example ‘Angles360A(1)-Angles360B(2)’, and so for the rest. (Note that in this line I forced them to both be column vectors.) (Make the appropriate changes to my code if you are using radian measure.)

This the angle equivalent of pdist2, so it should do what you want.

Star Strider
on 19 Feb 2016

My pleasure!

Thank you.

EDIT — More efficient versions of the angle conversion lines are:

Angles360 = rem(360+a, 360);

Angles2pi = rem(2*pi+a, 2*pi);

Opportunities for recent engineering grads.

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

Start Hunting!
## 3 Comments

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/269031-2d-matrix-indexing-for-element-wise-operation#comment_343979

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/269031-2d-matrix-indexing-for-element-wise-operation#comment_343979

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/269031-2d-matrix-indexing-for-element-wise-operation#comment_343980

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/269031-2d-matrix-indexing-for-element-wise-operation#comment_343980

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/269031-2d-matrix-indexing-for-element-wise-operation#comment_343981

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/269031-2d-matrix-indexing-for-element-wise-operation#comment_343981

Sign in to comment.