MATLAB discretization of a 2D circular surface

AI Thread Summary
The discussion focuses on modeling the magnetic force between two cylindrical permanent magnets using MATLAB. The user is currently facing inefficiencies in their code due to the method of discretizing the circular surfaces into square facets, which leads to unnecessary calculations for points outside the circle. A suggested solution involves creating a square lattice of points with the meshgrid function and applying a logical mask to identify points within the circular area. This approach streamlines the process by eliminating the need for complex if statements and reduces computational time. The conversation emphasizes the importance of efficient coding practices in MATLAB for better performance.
debwaldy
Messages
34
Reaction score
0
1. Hi,

I am trying to model the magnetic force between two cylindrical identical sized permanent magnets. I am using the Charge/Coulombian model to do this. This assumes that all of the "magnetic charge" is on the pole ends of the magnet, i.e. the flat surfaces at the top and bottom of each cylinder.

I am doing these calculations in MATLAB. I have managed to write code which produces a graph of force on one magnet, say M1 due to a second magnet, say M2, but this code is cumbersome and very slow so I need to find a more efficient way of discretizing the magnet surfaces.

At the moment I am dividing these circular surfaces into equal sized uniform square facets. Then I iterate along the X and Y axis, which is what is slowing me down, to get the central positioni of each facet, but this gives me some facets which are not inside the circular surfaces, so I am using an if statement and pythagoras to determine whether my point lies in my circle or is merely on the square which surrounds my circle.

This is all very slow so what I was goin to try and do was somehow use the radius of the circle to plot a circular surface area, and then divide this circle into the eqqual sized square facets as before. However I don't know how to read in this circular surface area so that I will have a 2D array which contains every single facet point - I am new to MATLAB

Any help or ideas would be much appreciated

Thank you
 
Physics news on Phys.org
One quick way is to create a square lattice of points with meshgrid, then use a simple if statement to get a logical mask that indicates whether each point is inside or outside the circle.

Example, where a = radius of circle and npts = # of squares you want to put across the diameter.

xvec = linspace(-a,a,npts);
[x,y] = meshgrid(xvec,xvec);
mask = x.^2 + y.^2 <= a^2 * ones(npts,npts);
% Mask has logical 1's for points inside the circle

% If you plot x,y, you'll see that all points outside the circle are masked out.

plot(x(mask),y(mask),'.')
axis('square')

BTW, please it's better not to post in bold letters. They are hard to read.
 
Back
Top