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

18 vues (au cours des 30 derniers jours)
SK
SK le 7 Déc 2016
Réponse apportée : SK le 11 Déc 2016
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

Réponse acceptée

SK
SK le 11 Déc 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.

Plus de réponses (1)

Walter Roberson
Walter Roberson le 7 Déc 2016
That is a major reason to code in functions and scripts: to be able to repeat code with different values.
  4 commentaires
SK
SK le 7 Déc 2016
Modifié(e) : SK le 7 Déc 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 le 7 Déc 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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by