Calling a script within another script

조회 수: 67 (최근 30일)
Sanjit Ganti
Sanjit Ganti 2017년 3월 8일
댓글: Sanjit Ganti 2017년 3월 9일
I am trying to call a script (say script2) within another script (say script1). But I have to declare a few variables in script1 before calling script2. When I try to do this, the script1 directly goes to calling script2, without declaring the variables in between. How to overcome this?
{clear
xq=2; yq=2;
script2}
  댓글 수: 4
Jan
Jan 2017년 3월 8일
@Sanjit: Please do not invent an own syntax containing curly braces to explain code in the forum. Prefer standard Matlab syntax, because this is understood here in general.
Sanjit Ganti
Sanjit Ganti 2017년 3월 9일
@Jan Simon: Sorry about that. Since this is my first question here, I didn't know about it. I will make sure about this from my next post.
Thank You

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2017년 3월 8일
편집: Jan 2017년 3월 8일
You can call one script from inside another without any problems:
% Script 1:
disp('I am script 1')
clear
a = 1;
b = 2;
Script2;
disp('Back in script 1')
disp(a)
disp(c)
And the second script:
% Script2
disp('I am script 2')
c = a + b
When you observe something like "script1 directly goes to calling script2, without declaring the variables in between", there must be another problem. Either you have not saved the script, or you run another script than you think you do. Use the debugger to find out the details: Set a breakpoint in the first line of the script and step through the code line by line.
If the 2nd script contains a clear, all formerly declared variables are deleted. It is a good prgramming pratice to avoid scritps and use functions instead. This allows to control the input and output of variables accurately and without any side-effects. Then the clear command can be omitted completely.
  댓글 수: 1
Sanjit Ganti
Sanjit Ganti 2017년 3월 9일
Hey, thank you very much for your answer. Whatever you pointed out in the last paragraph of your answer was exactly what was happening. Once again thank you for such a detailed answer.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2017년 3월 8일
You should get rid of the "clear" statements in your scripts.
  댓글 수: 1
Sanjit Ganti
Sanjit Ganti 2017년 3월 9일
Hey, that really helped. I was using a "clear" statement in the beginning of the script2, which is getting rid of the already declared variables in the script1. Thank you for pointing it out.
Now my question sounds very silly to me..

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Scope Variables and Generate Names에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by