How can I send data from one function to another?

조회 수: 6 (최근 30일)
Michael cornman
Michael cornman 2016년 7월 5일
댓글: James Tursa 2016년 7월 7일
I have a function that is reading values from a .txt file using fscanf, and storing those values in an array.
Now I have another function that needs to use that array, but I am getting an error that says the variable does not exist.
Research tells me that after a function is done running, the variable leaves the workspace.
How can I pass this data into the 2nd function?
Thank you!
  댓글 수: 1
amine&&
amine&& 2016년 7월 5일
What is the data type that is in the .txt file?

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

채택된 답변

James Tursa
James Tursa 2016년 7월 6일
You can pass the variable out from the first function and pass it in to the other function. E.g.
% File fun1.m
function result = fun1
result = rand(3);
end
% File fun2.m
function fun2(x)
disp(x)
end
And then at the command line:
>> x = fun1
x =
0.7577 0.6555 0.0318
0.7431 0.1712 0.2769
0.3922 0.7060 0.0462
>> fun2(x)
0.7577 0.6555 0.0318
0.7431 0.1712 0.2769
0.3922 0.7060 0.0462
Another way is to use the 'userdata' property of the 0 process. E.g.,
% File fun3.m
function fun3
result = rand(3);
set(0,'userdata',result);
disp(result);
end
% File fun4.m
function fun4
x = get(0,'userdata');
disp(x)
end
Then at the command line:
>> fun3
0.0971 0.3171 0.4387
0.8235 0.9502 0.3816
0.6948 0.0344 0.7655
>> fun4
0.0971 0.3171 0.4387
0.8235 0.9502 0.3816
0.6948 0.0344 0.7655
  댓글 수: 3
Michael cornman
Michael cornman 2016년 7월 6일
Using the 'UserData' property of the 0 process works for calling 1 variable. What if I wanted to call more?
James Tursa
James Tursa 2016년 7월 7일
You can use a structure. E.g., the fieldname of the structure would indicate which variable you are dealing with. In this case when you want to set a variable, you would get the structure first, assign the field to your new value, then set the structure back.

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2016년 7월 6일

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by