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

조회 수: 14 (최근 30일)
SK
SK 2016년 12월 7일
답변: SK 2016년 12월 11일
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