AI Chat Playground generated an interactive plot with a slider and a bug
古いコメントを表示
I asked MATLAB AI Chat Playground to generate an interactive plot with a slider.
With slight modification, the code runs (in desktop environment) , but the plot is updated only when the slider value
is increased, not when decreased. Can anyone spot why?
% Create the UI figure
fig = uifigure('Name', 'Interactive Sin Plot');
fig.Position(3:4) = [400 300];
% Create the plot
ax = uiaxes(fig);
ax.Position = [50 50 300 150];
x = linspace(0, 2*pi, 1000);
y = sin(x);
line(ax, x, y, 'Color', 'b', 'LineWidth', 2);
% Create the slider
slider = uislider(fig);
slider.Position = [50 200 300 3];
slider.Limits = [0.1 10];
slider.Value = 1;
slider.MajorTicks = [0.1 1 10];
slider.ValueChangedFcn = @(sld, event) updatePlot(sld.Value, ax);
% Function to update the plot based on the slider value
function updatePlot(period, ax)
x = linspace(0, 2*pi*period, 1000);
y = sin(x);
line(ax, x, y, 'Color', 'b', 'LineWidth', 2);
end
採用された回答
その他の回答 (1 件)
DGM
2024 年 4 月 12 日
Try just updating the existing line object instead of creating new line objects.
% Create the UI figure
fig = uifigure('Name', 'Interactive Sin Plot');
fig.Position(3:4) = [400 300];
% Create the plot
ax = uiaxes(fig);
ax.Position = [50 50 300 150];
x = linspace(0, 2*pi, 1000);
y = sin(x);
hl = line(ax, x, y, 'Color', 'b', 'LineWidth', 2);
% Create the slider
slider = uislider(fig);
slider.Position = [50 200 300 3];
slider.Limits = [0.1 10];
slider.Value = 1;
slider.MajorTicks = [0.1 1 10];
slider.ValueChangedFcn = @(sld, event) updatePlot(sld.Value, hl);
% Function to update the plot based on the slider value
function updatePlot(period, hl)
x = linspace(0, 2*pi*period, 1000);
y = sin(x);
hl.XData = x;
hl.YData = y;
end
3 件のコメント
Tomazz
2024 年 4 月 12 日
The reason is because the axes extents are set implicitly by the range of the data plotted by all the line objects, and the old line objects don't get deleted. As a consequence, the axes limits only change if you create a set of XData which spans a larger interval than any prior plot. The new "invisible" lines are there, they're just coincident with the existing lines over a shorter interval.
You can see the behavior in action if you use a different line color for each plot.
line(ax, x, y,'color',rand(1,3),'LineWidth', 2);
FWIW, chart.line primitives created by plot() have a few different interactions with their parent axes upon creation when compared to graphics.line primitives created by line(). They're similar, but just bear in mind they're not really expected to be the same.
Tomazz
2024 年 4 月 15 日
カテゴリ
ヘルプ センター および File Exchange で Develop Apps Programmatically についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!