MATLAB: function point_cloud

Question: Write a function called point_cloud that takes one scalar as an input argument (the function does not have to check the format of the input) and has no output argument.

If it is called like this, point_cloud(100), then it plots 100 points. Each point has a random x coordinate and a random y coordinate, each of which is gotten by a call to randn, which uses a normal distribution with a standard deviation equal to 1. The range of the plot axes should be −5 to 5 in both the x and y dimensions. The grid should be turned off. The points should be plotted and displayed one at a time by calling plot with only one point specified and, following the call of plot, by a call of drawnow, which causes the point to be plotted immediately. The command hold on should be included so that all previous points are retained when a new point is plotted.

Figure 2.41 shows an example view of the plot after point_cloud(100000) has completed its point-by-point plotting on a Mac. (Note that on Windows the points are much larger. Also note that it takes a long time to plot this many points with drawnow. Finally, try zooming in the middle.)

Figure 2.41

My Code:

    function point_cloud(N)

    hold on
    grid off
    axis([-5,5,-5,5])
    for ii = 1:N
        plot(randn(ii));
        drawnow;
    end

I know this is wrong, but I'm not sure how to solve this problem. Can someone help?

Solved code:

    function point_cloud(N)

    figure
    hold on
    grid off
    axis([-5,5,-5,5])
    x = randn(N,1);
    y = randn(N,1);
    for ii = 1:N
        plot(x(ii),y(ii),'b.');
        drawnow;
    end

Upvotes: 1

Views: 135

Answers (2)

Cornelis de Mooij
Cornelis de Mooij

Reputation: 94

To add to the other answer, here is the code as a function, with the added functionality that the points are one pixel on Windows as well:

function point_cloud(N)
    f = figure;
    x = randn(N,1);
    y = randn(N,1);
    scatter(x,y,1/36,'b.');
    f.GraphicsSmoothing = 'off';
    grid off
    axis([-5,5,-5,5])
    axis equal
end

The size of the markers is set with the third parameter of scatter: 1/36. The graphics smoothing of the figure needs to be set to 'off' as well, to make sure that the pixels don't become blurry or lighter.

Here's a 3D version:

function point_cloud3D(N)
    f = figure;
    x = randn(N,1);
    y = randn(N,1);
    z = randn(N,1);
    scatter3(x,y,z,1/36,'b.');
    f.GraphicsSmoothing = 'off';
    grid off
    axis([-5,5,-5,5,-5,5])
    axis square
    view(3)
end

Upvotes: 0

Hein Wessels
Hein Wessels

Reputation: 947

You do not need the for loop at all. And drawing the plot each iteration is very time consuming. How about rather using the scatter function.

figure
hold on
grid off
axis([-5,5,-5,5])
x = randn(N,1);
y = randn(N,1);
scatter(x,y,'b.')

This will be a lot faster.

Upvotes: 2

Related Questions