Using a Variable between different functions

조회 수: 5 (최근 30일)
Gözde Üstün
Gözde Üstün 2020년 6월 21일
댓글: Gözde Üstün 2020년 6월 25일
Hello,
I have this two function. evAlice and evBob were defined in CHSH_ but I need to access themin basis function. But I could not know how can I access to evAlice and evBob in basis fucntion.
function [coin, I] = CHSH_(sigma_x,sigma_z)
ev1_of_alice = sigma_x;
ev2_of_alice = sigma_z;
ev1_of_bob = sigma_x+sigma_z;
ev2_of_bob = sigma_x-sigma_z;
evAlice=[sigma_x,sigma_z];
evBob=[sigma_x+sigma_z,sigma_x-sigma_z];
... %function is too long so I just put the relevant part
end
function [basis_mat] = basis(measurement_setting)
% Choose the correct basis depending on the
% measurement setting. If you change the observables,
% these are obtained by diagonalization
switch measurement_setting
case evAlice(0)
basis_mat = [1, 1; 1,-1]/sqrt(2);
case evAlice(1)
basis_mat = [1, 0; 0, 1];
case evBob(0)
basis_mat = [ 1+sqrt(2), 1-sqrt(2); 1, 1];
case evBob(1)
basis_mat = [-1-sqrt(2),-1+sqrt(2); 1, 1];
end
end

채택된 답변

the cyclist
the cyclist 2020년 6월 21일
편집: the cyclist 2020년 6월 21일
You can pass them out of the first function:
function [coin, I, evAlice, evBob] = CHSH_(sigma_x,sigma_z)
and into the second one by calling it like this
basis(measurement_setting, evAlice, evBob)
and defining it as
function [basis_mat] = basis(measurement_setting, evAlice, evBob)
Alternatively, you could define those variables as global in scope, in both functions, but that is generally a bad idea.
  댓글 수: 4
Stephen23
Stephen23 2020년 6월 22일
편집: Stephen23 2020년 6월 22일
"Instad of that can I use global variable or is this better ?"
Global variables: slower, more buggy, harder to debug, obfuscate the code intent.
Input/output variables: faster, easier to debug, recommended by the MATLAB documentation as "best practice":
If you have lots of arguments then put them into a structure and pass that.
Gözde Üstün
Gözde Üstün 2020년 6월 25일
Thank you very very much : -) @the cyclist and @Stephen Cobeldick

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by