How can some elements in matrix representation that satisfies a cutoff function be deleted in MATLAB?
X=(-5:.5:5)
Z=(-3:.5:3)
[x z]=meshgrid(X,Z)
The cutoff function that must delete the wanted elements is a circle w开发者_开发百科ith radius 1 (x-1)^2+(z-1)^2<=1 How can we manage a loop to put those elements 0 in the output data?
I'm first going to assume that x
and z
represent the coordinates at which some 2-D function f
will be evaluated to generate your output. Given that x
and z
end up being 13-by-21 matrices in your example, your output from f
should be 13-by-21 as well. You can then find a logical index indicating the points that are inside your circle and use this index to set the points in the output matrix to be zero:
output = f(x,z); %# Compute your output, which should be a 13-by-21 matrix
index = (x-1).^2 + (z-1).^2 <= 1; %# Logical index of elements inside the circle
output(index) = 0; %# Set the output values inside the circle to 0
I think what you are looking for is this:
for i=1:size(x,1)
for j=1:size(x,2)
if ((x(i,j)-1)^2+(z(i,j)-1)^2<=1)
x(i,j) = 0;
y(i,j) = 0;
end
end
end
I hope this code is easy enough for you to understand what it does - if not you should take a programming class somewhere or sit down with a book.
Now, if the above answer is what you were looking for, take my word for it that gnovice's answer (a mix of edit 2 and edit 3 actually) showed the way how to do this much smarter in MATLAB:
radius = 1;
index = (x-1).^2 + (z-1).^2 <= radius^2; %# Logical index of elements inside the circle
x(index) = 0; %# Set the x values inside the circle to 0
z(index) = 0; %# Set the z values inside the circle to 0
Hope this helps - otherwise I'm giving up ;-).
精彩评论