Display different graphs from a dropdown menu

14 views (last 30 days)
I want to be able to use a dropdown menu to display different graphs. I have been able to generate the graphs and the dropdown menu. However, when I go to use the dropdown menu I get an error which will be described below. Here is my code:
clear
clc
% create figure and components
fig = uifigure;
ax = uiaxes('Parent', fig, 'Position', [10 10 400 400]);
% Create a plot
x = (-100:100)';
y.A = x.^2;
y.B = x.^3;
p = plot(ax, x, y.A);
p.YData = y.A;
% Create a dropdown component
dd = uidropdown(fig, 'Position', [430 210 100 22],...
'Items', {'A', 'B'},...
'Value', 'A',...
'ValueChangedFcn', @(dd, event) selection(dd,p));
% Create ValueChangedFcn callback
function selection(dd, p)
val = dd.Value;
p.YData = val;
end
The error that I get is as follows:
Value must be a vector of numeric type
Error in dropDownTest2>selection (line 29)
p.YData = val;
Error in dropDownTest2>@(dd,event)selection(dd,p)
Error using matlab.ui.control.internal.controller.ComponentController/executeUserCallback (line 378)
Error while evaluating DropDown PrivateValueChangedFcn.
Thanks for your help
  2 Comments
Nev Pires
Nev Pires on 10 May 2019
To be honest, I wanted val to be equal to whatever I selected from the dropdown menu. If "A" was selected, it would display the graph: y.A, and if "B" was selected it would display the graph: y.B. The only way I could get anything to display in the first place is with this code. I have no idea how to associate the dropdown menu selections with the respective graphs I want to plot.

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 10 May 2019
This should do what you're describing. Let me know if you have any questions.
% create figure and components
fig = uifigure;
ax = uiaxes('Parent', fig, 'Position', [10 10 400 400]);
% Create a plot
x = (-100:100)';
y.A = x.^2;
y.B = x.^3;
p = plot(ax, x, y.A);
% p.YData = y.A; %No need for this line
% Create a dropdown component
dd = uidropdown(fig, 'Position', [430 210 100 22],...
'Items', {'A', 'B'},...
'Value', 'A',...
'ValueChangedFcn', @(dd, event) selection(dd,p,y));
% Create ValueChangedFcn callback
function selection(dd, p, y)
switch dd.Value
case 'A'
val = y.A;
case 'B'
val = y.B;
otherwise
error('Did not recognize selection.')
end
p.YData = val;
end

More Answers (0)

Categories

Find more on Specifying Target for Graphics Output in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!