![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1557449/image.png)
Why is my plot showing nothing?
2 views (last 30 days)
Show older comments
Why my code plot nothing inside the loop, but the similar code work outside the loop, I appreciate your help. I MUST plot solid line '-' inside the loop...
--------------- This is the code ---------------
x=1:100;
y=1:100;
z=1:100;
hold on
for i=1:length(x)
plot3(x(i),y(i),z(i),'-')
end
figure()
plot3(x(:),y(:),z(:),'-')
0 Comments
Accepted Answer
Shubham
on 1 Dec 2023
Hi Mohammad,
The issue with your code is that within the loop, you're plotting individual points using plot3 by specifying x(i), y(i), z(i) with a '-' line style. However, MATLAB requires at least two points to draw a line. When you provide only a single point, MATLAB does not draw anything because a line cannot be defined with a single point.
To plot a solid line within the loop, you need to accumulate the points and plot the line from the start to the current point in the loop. Here's how you can modify your loop to draw a line that extends with each iteration:
x = 1:100;
y = 1:100;
z = 1:100;
hold on
for i = 1:length(x)
plot3(x(1:i), y(1:i), z(1:i), '-')
drawnow % Optional, to update the figure with each iteration
end
This code will plot a line from the start to the i-th point at each iteration, effectively building up the line as the loop progresses.
Now, if you want to see the line being drawn progressively, you can include drawnow inside the loop. This will force MATLAB to update the figure window with each iteration of the loop. However, be aware that this can be quite slow if you have a large number of points or if you're running the loop many times.
For the code outside the loop, it works because you're providing the full vectors x(:), y(:), z(:) to plot3 along with the '-' line style, which tells MATLAB to connect all the points in the vectors with a line, resulting in a continuous line being drawn.
Here is the screenshot of the plot output:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1557449/image.png)
More Answers (0)
See Also
Categories
Find more on Graphics Performance in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!