Reputation: 1481
I want to write a script that automatically executes specific sections of a the script and skips all other sections. Here's my example code:
clear all; close all; clc;
to_plot=input('Which values do you want to plot: ','s');
x=linspace(0,100);
%% SECTION 1
y1=x;
figure('Position', [100, 100, 1024, 768]);
plot(x,y1);
print( gcf, '-dpng', 'y1.png');
%% SECTION 2
y2=x.^2
figure('Position',[100, 100, 1024, 768]);
plot(x,y2);
print( gcf, '-dpng','y2.png');
%% SECTION 3
y3=x.^3
figure('Position',[100, 100, 1024, 768]);
plot(x,y3);
print( gcf, '-dpng','y3.png');
Now i want to be able to make an input like to_plot=y1,y3
and the script automatically only executes the 1st and 3rd section and just skips the 2nd and all (possible) other sections. Does anyone have an idea how to achieve this Without adding an if
-condition to each section?
EDIT: And if someone feels like making me really happy, he or she could add a checkbox menu in which I can check all the values i want to plot.
Upvotes: 1
Views: 55
Reputation: 6187
The easiest is probably to use if
statements. Here I use str2num
to convert the output of input
to a vector of numbers. I then use any
to check if the value we want is contained within the returned vector from str2num
.
plotting = str2num(input('Which values do you want to plot? ', 's'));
if (any(plotting == 1))
fprintf(1, 'Plot y1\n');
end
if (any(plotting == 2))
fprintf(1, 'Plot y2\n');
end
if (any(plotting == 3))
fprintf(1, 'Plot y3\n');
end
Sample outputs for the above would be
>> plotting_fun
Which values do you want to plot? 1 3
Plot y1
Plot y3
>> plotting_fun
Which values do you want to plot? 1,3
Plot y1
Plot y3
As a side note, I like any
because it can be used to make your code really easy to read.
It does what it says on the tin!
Upvotes: 3