Syntax to comment/uncomment line(s) of code in a Matlab script

25 views (last 30 days)
I am writing a code for a class project. It requires me to do same calculations for two different cases based on user input. I was going to code it in a way that the program would ask user which case to follow. However, I found out that because of various parameters related to each other, this will be extremely difficult. However, I thought of another way to do this but I don't know if I could do it in Matlab. So the way I want to code is, I would ask the user to choose one of the two cases, and based on his input, I would comment or uncomment OR read or skip a bunch of lines or line numbers. Is this possible to do in a running Matlab script? I know how to comment/uncomment a line in a Matlab script that's not running, but I was wondering if there is a syntax to skip reading certain lines in a running Matlab script.

Accepted Answer

Matt Kindig
Matt Kindig on 14 Mar 2013
There is no way (at least as far as I am aware) to comment out lines programatically. However, even if you could, this is almost certainly not a good approach for what you are trying to do.
Instead, I think the easiest way is just to wrap it in an if statement
if (user_input_condition_1)
%code to run for case 1
else
%code to run for case 2
end
You can also use switch statements instead of the if statements--the approach is similar.

More Answers (2)

Jason Ross
Jason Ross on 14 Mar 2013
Edited: Jason Ross on 14 Mar 2013
I would use an "if" statement combined with some functions.
The "if" provides the control flow, and the functons called prevent duplication of code.
For example, assuming "a" is the result of your question:
answer = 0;
if a == true
p1 = function1;
p2 = function2;
p3 = function3;
answer = p1+p2+p3;
else
p1 = function1;
p2 = function3;
answer = p1+p2;
end
disp(answer)
function o1 = function1
o1 = 1;
end
function o2 = function2
o2 = 2 + function1;
end
function o3 = function3
o3 = 3;
end

Image Analyst
Image Analyst on 14 Mar 2013
Sometimes I'll have a flag that I can set to do certain lines of code, like fprintf() debug statements. I can have an if statement lots of places in the code and just set the flag at the beginning.
showDebugMessages = true; % Set to true or false
if showDebugMessages
fprintf(.........
% other conditional code.....
end
% More code that always executes.
% Now conditional code again:
if showDebugMessages
fprintf(.........
% other conditional code.....
end

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!