how can an function containing structure data can be used in main code while main code also containing same/different structure.

Let say i have main code containg structure name str1 and it have two fields a and b.
In the main code i call an function which also contain structure name str2 (or even same structure str1 )having multiple fields c,d,e...
Now if i need to use one of the field data of str2 with str1 it give me the error of (Refer to the non existance feild and some time undefine variable ).
for example:
str1.a=randi([0,10],1,8);
str1.b=randi([-100,-10],1,8);
practice2; (call function name practice2 while practice2 have)
function c = practice2;
str2.d= randi([0,10],1,8);
c=str2.d
end.;
str1.p=str1.a+str2.d
%or str1.p=str1.a+c

 Accepted Answer

function c = practice2;
str2.d = randi([0,10],1,8);
c = str2.d;
end
and then:
str1.a=randi([0,10],1,8);
str1.b=randi([-100,-10],1,8);
val = practice2()
str1.p = str1.a + val

More Answers (1)

Variables in a function are in their own scope internal to the function, only what is returned tot the caller is available to the caller.
If you need something from the function, the function must be written to return that something and the call must allow for there to be a local variable on the LHS of the expression in which to store it (or use the return values in an expression).
Thus variable names inside functions are totally separate from and independent of the names chosen for variables in either main script or in another function.
y=practice2; % call the function, return its struct as variable y
Read the "Getting Started" documenation on Programming Scripts and Functions to get an overview and then study the sections of Scripts vs Functions to grasp the concept of scope.

Categories

Community Treasure Hunt

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

Start Hunting!