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

14 次查看(过去 30 天)
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

采纳的回答

SK
SK 2016-12-11
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.

更多回答(1 个)

Walter Roberson
Walter Roberson 2016-12-7
That is a major reason to code in functions and scripts: to be able to repeat code with different values.
  4 个评论
SK
SK 2016-12-7
编辑:SK 2016-12-7
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 2016-12-7
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by