Update a value in a struct in another function

조회 수: 6 (최근 30일)
Jay
Jay 2024년 6월 20일
댓글: Jay 2024년 6월 20일
I have a struct which is initialized by this:
function myStruct = defult_config
myStruct.myLenth = 1;
end
myStruct.myLength = 1 is an initial value and it needs to be updated by another fuction, myUpdate:
function out = myUpdate(myStruct)
myStruct.myLength = 2;
out = [];
end
However, myUpdate doesn't update myStruct and myStruct.myLength is still shown 1.
Any way to update a value in a struct by another function?

채택된 답변

dpb
dpb 2024년 6월 20일
Variables in functions are local to the function and you don't return the struct; in fact in myUpdate you don't return anything at all...
function myStruct = myUpdate(myStruct)
myStruct.myLength = 2;
end
You would have to use this in some context like
workingStruct=default_config;
... % whatever else
workingStruct=myUpdate(workingStruct);
... % more stuff...
This is going to be an awkward use pattern one imagines and unless there's a lot more than shown going on, simply writing
workingStruct=default_config;
... % whatever else
workingStruct.myLength=newvalue;
... % more stuff...
inline will probably be as legible code and easier...because unless the update value is a constant as shown, you're not providing it in the updating function and if you have to also add it as the second argument, then may as well just go ahead and update the struct itself directly.
Now, if there are some 20 other values as well, then mayhaps some similar structure may be desireable.
  댓글 수: 1
Jay
Jay 2024년 6월 20일
Thanks for clarification on how MATLAB works internally.

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

추가 답변 (1개)

Matt J
Matt J 2024년 6월 20일
편집: Matt J 2024년 6월 20일
You must return the modified myStruct from myUpdate():
myStruct.myLength = 1
myStruct = struct with fields:
myLength: 1
myStruct = myUpdate(myStruct)
myStruct = struct with fields:
myLength: 2
function myStruct = myUpdate(myStruct)
myStruct.myLength = 2;
end

카테고리

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