更快的方法在matlab中“for循环”

时间:2016-12-05 13:11:46

标签: matlab loops

我想用圆点填充单位圆。但是我写的代码非常慢。 Matlab可以更快地运行吗?

y = linspace(-1, 1, 200);
x = linspace(-1, 1, 200);
for i = 1: length(x)
    for j = 1: length(y)
        if (x(i)^2 + y(j)^2 < 1)
            plot(x(i),y(j),'.');               
        end
    end
end

1 个答案:

答案 0 :(得分:3)

您可以使用x创建两个矩阵(ymeshgrid),而不是循环遍历xxyy的每个排列。两者中的值是xy值的唯一组合。然后,您可以使用这些矩阵一次评估条件(xx.^2 + yy.^2 < 1)。这将产生一个大小为xx的逻辑数组,我们可以用它来绘制单位圆内的点。

[xx,yy] = meshgrid(x, y);
inside = xx.^2 + yy.^2 < 1;

% Now plot just these points
plot(xx(inside), yy(inside), '.');

enter image description here