How to re-run portions of code with updates variables?

10 views (last 30 days)
Hello, for my lab assignment we have to graph a few equations and then change the variable value and re-graph. For my previous labs, I have been copying the code and updating the values. However, I was wondering if it was possible to only update the variables and call a certain portion of the code with the updated values? Example:
% % Run portions of code after updating variables
a = 3; b = 7; x = linspace(0,200,1001); % initial values
y = sin((a+x)/4) + b; % some equations
z = cos((b.*x)/50) + 2*a;
figure;
plot(t, y, 'b', t, z, 'r'); ylim([4 9]);
% re-run code with a = 6 and b = 4
% update values of a and b in this line
% re-run lines 2-8 with updated a and b
Any help would be appreciated

Accepted Answer

SK
SK on 11 Dec 2016
I ended up doing something similar to what Walter Roberson suggested, i.e. using a for loop. Initially, I wanted to get the plots into a subplot, but realized that would be too complicated. The code similar to what I did is below. (Note: I had to do three cases of tau and two cases of M).
for tau = [T, 5*T, 10*T]
% computations of equations for three cases of tau
for M = [M1, M2]
% commutations for two cases of M
% plot of equations
end
end
Once executed the code, I ended up with six individual graphs. Once the code was published to PDF then everything looked alright. Using the for loop shortened my code from 200+ lines to just 30-something lines.

More Answers (1)

Walter Roberson
Walter Roberson on 7 Dec 2016
That is a major reason to code in functions and scripts: to be able to repeat code with different values.
  4 Comments
SK
SK on 7 Dec 2016
Edited: SK on 7 Dec 2016
Thank you. Although, when I try to run my code I am getting the following error:
function oops_I_did_it_again(a, b)
Error: Function definitions are not permitted in this context.
I am not sure how to tackle this.
Jiro Doke
Jiro Doke on 7 Dec 2016
There was a typo in your original code. plot(t,y,... should be plot(x,y,...
Either way, create a single file (lab7.m) like this:
function lab7
a = 3; b = 7;
oops_I_did_it_again(a, b);
a = 6; b = 4;
oops_I_did_it_again(a, b);
function oops_I_did_it_again(a, b)
x = linspace(0,200,1001); % initial values
y = sin((a+x)/4) + b; % some equations
z = cos((b.*x)/50) + 2*a;
figure;
plot(x, y, 'b', x, z, 'r'); ylim([4 9]);
Then run the code:
>> lab7

Sign in to comment.

Categories

Find more on Programming 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!