MATLAB Answers

How can I run a matlab program N times using a different value of one of my variables

조회 수: 9(최근 30일)
Kareemmasud
Kareemmasud 14 Jun 2019
댓글: Kareemmasud 18 Jun 2019
Imagine a scenerio where I have a matlab program with N variables. I then want to make one of the variables a vector so I can run the program many times (length of the vector). I just intend to do this by calling the program in a loop. But each time I do that it's indicating that the variable be defined in the original program.

  댓글 수: 8

표시 이전 댓글 수: 5
Adam Danz
Adam Danz 14 Jun 2019
@gonzalo Mier, You sould copy that to the answers section and get credit for your solution.
To add to gonzalo's solution, below is the loop version which does the same thing. gonzalo's solution is the way to go but sometimes loops are more intuitive for beginners.
x_s=0:.1:1;
xpos=linspace(-100,100,3);
Ein0 = zeros(numel(x_s),numel(xpos));
for i = 1:numel(x_s)
lambda=750;
k=2*pi/lambda;
Ein0(i,:)=exp(1i*k*(xpos-x_s(i)));
end
Kareemmasud
Kareemmasud 14 Jun 2019
Thanks Gonzalo and Adam. As I mentioned earlier, the code contains 100s of loops already and I would prefer to run the script in a loop. What I pasted above is just an example of the scenario and is not in anyway simple as the real program.
gonzalo Mier
gonzalo Mier 14 Jun 2019
Thank you Adam, but I had the feeling it was not over.
mmmmm... ok, can you please add the code of the real problem or a closer example of your real problem so we have some idea about how to solve your question?
Help us to help you :)

로그인 to comment.

채택된 답변

per isakson
per isakson 15 Jun 2019
편집: per isakson 15 Jun 2019
Assumptions:
  • You have a script. Lets call it myScript.
  • The first line of myScript is clear all
  • Near the top of myScript there is an assignment, e.g input = 17;.
  • In myScript a result is assigned to a variable, e.g. output = expression;
  • Now you want to run myScript with different values, e.g. [2,3,5,7,11,13,17], of the variable, input
Procedure
  • In myScript comment out the lines clear all and input = 17; Result: % clear all and % input = 17;
  • Create a script in a new file, e.g. loop_over_myScript
%% loop_over_myScript
vector = [2,3,5,7,11,13,17];
out_vector = [];
for vec = vector
input = vec;
myScript
% ignore the warning about growing in the loop
out_vector = [ out_vector, output ];
end
  • Beg that no variables named, vector, vec or out_vector, exist in myScript. (Renaming them vector__, vec__ and out_vector__ might decrease the risk of name collision.)
  • Run loop_over_myScript
  • Inspect out_vector, e.g with the Variables Editor
  • Run whos and be horrified by all the variables that litters the base workspace.

  댓글 수: 1

Kareemmasud
Kareemmasud 18 Jun 2019
Thanks @Per Isakson. The program did exactly what I wanted.

로그인 to comment.

추가 답변(0개)

이 질문에 답변하려면 로그인을(를) 수행하십시오.


Translated by