Adding Drop Down Control
Mostrar comentarios más antiguos
I am trying to add a Drop Down Control to my code that allows me to display only one signal (Sawtooth, Square, Triangle, Rectangle). I choose (Drop Down) from (Control) in the top bar. But I have no idea where to insert it in my code or how to make it work. Here is the code:
fs = 10000;
t = 0:1/fs:1.5;
x1 = sawtooth(2*pi*50*t);
x2 = square(2*pi*50*t);
subplot(2,1,1)
plot(t,x1)
axis([0 0.2 -1.2 1.2])
xlabel('Time (sec)')
ylabel('Amplitude')
title('Sawtooth Periodic Wave')
subplot(2,1,2)
plot(t,x2)
axis([0 0.2 -1.2 1.2])
xlabel('Time (sec)')
ylabel('Amplitude')
title('Square Periodic Wave')
Respuesta aceptada
Más respuestas (1)
Benjamin Kraus
el 30 de Mayo de 2025
Editada: Benjamin Kraus
el 30 de Mayo de 2025
Write your code like this:
fs = 10000;
t = 0:1/fs:1.5;
wave = "Sawtooth";
f = str2func(lower(wave));
x = f(2*pi*50*t);
plot(t,x)
axis([0 0.2 -1.2 1.2])
xlabel('Time (sec)')
ylabel('Amplitude')
title(wave + ' Periodic Wave')
Then highlight the word "Sawtooth" (including the quotation marks) and choose "Control" -> "Drop Down".

What you should see is this:

Now right-click on the drop-down and choose "Configure Control". You can add your additional strings there. "Item labels" is what users of the drop-down will see, and the "Item values" is the code that will be used. Make sure to include double-quotes in the "Item values".

Now when you pick a different item from the drop-down, your code will re-run with the chosen function.
Note: This will work for "Square" and "Sawtooth", but rectangle is a function in MATLAB that serves a different purpose (drawing rectangles in figures), so you would need to write your own implementation of that (and give it a different name, to avoid conflicting with the existing rectangle function), and triangle is also not a function, so you would need to write that.
2 comentarios
Benjamin Kraus
el 30 de Mayo de 2025
Alternatively, a bit more advanced uses function handles instead of strings:
Write your code like this:
fs = 10000;
t = 0:1/fs:1.5;
f = @sawtooth;
x = f(2*pi*50*t);
plot(t,x)
axis([0 0.2 -1.2 1.2])
xlabel('Time (sec)')
ylabel('Amplitude')
title([func2str(f) ' Periodic Wave'])
And when configuring the control, it should look like this:

(Converting the "s" to uppercase for the title is left as an exercise for the reader.)
Benjamin Kraus
el 30 de Mayo de 2025
Categorías
Más información sobre Descriptive Statistics en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

