How to get menu to call code sections

3 views (last 30 days)
I am working on a assignment where I am manipulation an image. All the code is written in code sections corresponding to the task number.
The last task on the assignment is to add a menu which runs the code for the different task.
For example: Task 2: Show image. Code: imshow(A).
Is there a way I can call the different code sections with my menu, can I create functions and call them, or do I need to copy all my code into the switch case section of my menu? The menu is the last task, therefore it is currently on the bottom of my code.
%% Task 1: Load the image data
A = imread('butterfly.jpg');
%% Task 2: Show image
function taskTwo
imshow(A);
end
%% Task 10: Menu
choice = 1;
while choice ~= 7
choice = menu('Toolbar', 'Task 2', 'Task 5', 'Task 6', 'Task 7', 'Task 8', 'Task 9', 'Exit');
switch choice
case 1
taskTwo
case 7
close all
end
end
  1 Comment
Adam
Adam on 19 Sep 2019
Edited: Adam on 19 Sep 2019
Creating functions is the way to go definitely, as you appear to have already done in one case of the pasted code, although whether you can define a function in the middle of a script or not I'm not entirely sure, I've never tried. You can define them all at the end certainly, or in their own file.
You also need to take care of input arguments though unless you use nested functions, which I'm fairly sure you can only do if the top level if is a function, not a script. Otherwise you'd need to pass the arguments in to each function.

Sign in to comment.

Accepted Answer

Aleksander Vae Haaland
Aleksander Vae Haaland on 19 Sep 2019
I got it working. The tasks look a little out of order, but otherwise it works great!
I defined all the variables I needed at the top of the code. Then wrote the menu, as seen above. Then I defined all the functions below the menu. I don' t need to define the variable A in every function because I call the function with the variable as the argument.
When trying to define a function mid-code, it will display an error telling you to define all functions at the end of the code.
Some dubstep and a energy drink later I figured out how this works.
% Task 1: Load the image into variable A
A = imread('butterfly.jpg');
% Task 10: Menu
choice = 1;
while choice ~= 7
choice = menu('Toolbar', 'Oppgave 2', 'Oppgave 5', 'Oppgave 6', 'Oppgave 7', 'Oppgave 8', 'Oppgave 9', 'Exit');
switch choice
case 1
opp2(A);
case 2
opp5(A, R, G, B);
case 3
opp6(A);
case 4
opp7(A);
case 5
opp8(A);
case 6
opp9(A);
case 7
close all
end
end
% Task 2: Show image
function opp2(A)
figure;
imshow(A);
title('Bilde: butterfly.jpg')
end

More Answers (0)

Categories

Find more on Startup and Shutdown 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!