Adding Drop Down Control
이전 댓글 표시
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')
채택된 답변
추가 답변 (1개)
Benjamin Kraus
2025년 5월 30일
편집: Benjamin Kraus
2025년 5월 30일
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
Benjamin Kraus
2025년 5월 30일
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
2025년 5월 30일
카테고리
도움말 센터 및 File Exchange에서 Descriptive Statistics에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

