Pass objects into function

조회 수: 15 (최근 30일)
ac_bm_mat
ac_bm_mat 2022년 4월 28일
답변: Walter Roberson 2022년 4월 28일
classdef myClass
properties
data
end
methods
function h = myClass(data)
h.data = data ;
end
end
end
This is a class defined and I want to pass its object into a function like shown in the below:
h = myClass(0);
chg(h);
h.data
function chg(h)
h.data = h.data+2;
end
But line h.data prints 0 instead of 2. Why is that and where is the mistake in my code.

채택된 답변

Walter Roberson
Walter Roberson 2022년 4월 28일
You are using a value class, not a handle class. You change h.data inside the chg function, and that revised object gets returnedas a value. But you do not assign the results back over top of h; you just have semi-colon on the end of the line, so the result of the chg() function is not even displayed.
If you want to be able to call functions like that and have the properties changed without having to assign over-top of the existing object, then you need to switch to using a handle class.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by