Declaring a global variable to be used across functions and/or scripts in MATLAB

조회 수: 1 (최근 30일)
Hi
I've declared a global variables I in a script file named "xyz.m"
global I;
T_P = ones(1,I);
which will call the following function:
[C_Prob] = Calculate_C_Prob();
The function, which is in another file named Calculate_C_Prob.m is defined as:
function [C_Prob] = Calculate_C_Prob();
I = 5;
for i=1:I
t = prod(1-T_P(i+1:end));
end
Now, I is a constant and should remain I = 5 in both the script as well as in the function.
Is the above declaration of the global variable correct? Also, T_P (whose value can change with time) be accessible in the function file? If not, then how to make it so?

채택된 답변

Walter Roberson
Walter Roberson 2013년 9월 8일
global variables need to be declared in every function that they are used.
T_P will not be available to the function when you use that code. You could declare it global as well
  댓글 수: 8
Jan
Jan 2013년 9월 9일
@Syed: It is not useful to extract a tiny part of the error message, because important details are included in the complete message.
Image Analyst
Image Analyst 2013년 9월 9일
You need to pass in T_P when you call it from the command line. For example
result = Calculate_C_Prob(42)

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

추가 답변 (0개)

카테고리

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