How to change original variable inside function?
조회 수: 20 (최근 30일)
이전 댓글 표시
I want to change variable inside function, something simular to this c++ function:
void f(int &a){a+=2;}
I've heard handles can be useful here, but anything I tried only generated copy of variable, and was unable to change original. I'd use simple return values, but it's callback function and I can't return anything, at least as far as I know. Please help.
댓글 수: 0
채택된 답변
Stephen23
2015년 5월 9일
편집: Stephen23
2015년 5월 11일
MATLAB is pass-by-value, with some fancy inbuilt stuff to intelligently minimize memory usage. Variables are copied when they are changed, so when you make a change to that variable it will create a new copy.
If you need this variable outside of the callback, then you need to pass it somehow. There are several helper functions and ways of doing this:
http://matlab.wikia.com/wiki/FAQ#How_can_I_share_data_between_callback_functions_in_my_GUI.28s.29.3F
And if those do not help you then you should do a search of this forum, as this topic has been dealt with a thousand times before.
댓글 수: 0
추가 답변 (1개)
Image Analyst
2015년 5월 9일
Simply pass back the variable in the output list
function a = doubleit(a)
a = 2 * a; % Change a.
Now, in the calling routine
a = 5
a = doubleit(a);
Now a will have the new value you set it to inside the function, 10 in this case);
댓글 수: 6
Lunky Sucipto
2022년 5월 11일
@Image Analyst In your doubleit example, you use 'a' as both input and output. However my case is different:
function object = find(k)
% find the object from my data structure that has property k
object = item_with_property_k
end
After finding the object, I now need to modify the object. How can I do this? I'm going to read libpointer now, but I'm not sure about anything right now.
Image Analyst
2022년 5월 11일
@Lunky Sucipto just modify it. For example if it's a structure and you want to add a field "foundIt", just do
object.foundIt = true;
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!