How to re-run portions of code with updates variables?
Mostra commenti meno recenti
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
Risposta accettata
Più risposte (1)
Walter Roberson
il 7 Dic 2016
0 voti
That is a major reason to code in functions and scripts: to be able to repeat code with different values.
4 Commenti
Walter Roberson
il 7 Dic 2016
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(t, y, 'b', t, z, 'r'); ylim([4 9]);
That is one single file.
You could also consider using a "for" loop.
for ab = [3 6; 7 4]
a = ab(1); b = ab(2);
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]);
end
Jiro Doke
il 7 Dic 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
Categorie
Scopri di più su Mathematics in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!