- Each cell in a Live Script can be treated as a separate execution unit. When a cell is run, MATLAB processes the commands within it, and if there's a plotting command, it generates a plot in the output area.
- The "hold on" command tells MATLAB to retain the current plot and all its properties so that subsequent plots are added to the existing axes. "hold off" resets this behavior, allowing new plots to replace the existing one.
- When the first cell is executed, it plots the two lines on the same axes due to hold on. When the second cell is executed containing only "hold off", MATLAB considers this as a separate execution, which leads to generating a new figure if the Live Script environment interprets the "hold off" as a standalone command without a preceding plot.
'hold off' produces second plot in MATLAB Live Script
8 次查看(过去 30 天)
显示 更早的评论
I find a strange behaviour if I use 'hold on' and 'hold off' in a MATLAB Live Script. I tried out R2022b and R2023b.
If I put all my code into the first cell, it works as expected, i.e. it makes one plot.
But if I call 'hold off' in a new cell, it creates an additional plot.
First cell:
plot([1 2 3 4 5])
hold on;
plot([5 4 3 2 1 ])
Second cell:
hold off
yields TWO plots. Is this a bug? I always thought that 'hold on/off' is just a switch variable...
0 个评论
采纳的回答
Zinea
2024-9-30
The behaviour stated in the question is not a bug, rather it is an expected behaviour. The following points are to be noted in case of Live Scripts in MATLAB:
NOTE: Replacing the "hold off" by "hold on" in the separate cells would also result in plotting of separate plots.
Hope this resolves your query, cheers!
3 个评论
Zinea
2024-10-7
I think for the first scenario you meant:
"THREE diagrams, once the first and twice the second"
When calling hold off at the section break, the Live Editor tries to preserve the state of the current runtime figure by cloning it. This is because the content of the figure may be cleared. That explains the first scenario above.
The second scenario creates two figures as it is a MATLAB script instead of a MATLAB live script.
The third scenario occurs because when multiple commands are written in the same line in a live script, the commands run in order from left to right and each command overwrites the behaviour of the previous command. Hence, the output of only the last command is displayed, resulting in ONE figure. This behaviour may be checked by the following examples:
Example 1: The following when written in one cell, results in TWO figures, one figure for each line:
plot([1 3]);
plot([3 1]);
Example 2: The above commands when written inthe same line result in ONE figure, which is the output of the rightmost command:
plot([1 3]);plot([3 1]);
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Annotations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!