Struct with scope of multiple functions does not update in a nested function
13 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I have a structure that i update when a button is pressed in a gui like so:
S is the structure containing the gui S.struct is an existing struct
function []=callbackfun(varargin)
S=varargin{3};
editInfo=get(s.edit,'string'); %Get information from an text box
popInfo=get(s.pop,{'string','value'}) %Get info from a pop up
S.struct.(editInfo)=popInfo;
%I also add the variable popInfo to a another Popup, which i call here anotherPop
end
This updates the structure no problem within the function, but when I try to reference this in another callback function later, which looks like
function []=anothercall(varargin)
S=varargin{3}
val=get(S.anotherPop,{'string','value});
fieldName=val{1}{val{2}};
miscVar=getfield(S.struct,fieldName);
I have no other mention of S.struct, except when i initialize it at the very beginning of the function (even if i comment this out, i get the same problem) Yet, when i reach anothercall, S.struct.(editInfo) no longer exists.
Does anyone have any advice
0 Kommentare
Antworten (1)
TADA
am 5 Nov. 2018
Bearbeitet: TADA
am 5 Nov. 2018
I may be a little bit too late for the party but...
structures are value types, unlike handle classes, when you edit a struct inside a function it generates a copy of the original in the function workspace, therefore not affecting the original instance in the calling workspace.
it can get quite annoying but you need to either return it to the caller as an output argument, or save it as a property of a handle class passed to the function.
look at these two functions:
function foo(s)
s.x = 1:10;
end
function s = foo1(s)
s.x = 1:10;
end
now when invoking :
s = struct();
s.x = [];
foo(s);
disp(s.x); % nothing happened
x: []
foo1(s);
disp(s.x); % surprisingly, again nothing happened
x: []
% This is when the value of the struct edited by foo1
% is set back into the local workspace
s = foo1(s);
disp(s.x); % finally! s is updated.
x: [1 2 3 4 5 6 7 8 9 10]
0 Kommentare
Siehe auch
Kategorien
Mehr zu Structures finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!