Dobacetr
Dobacetr

Reputation: 33

MATLAB How to modify property of a value class from a method within a class that is within the original class?

I would like to create a class that stores, and is able to modify a vector. Looks something like this:

classdef vect3d
      properties
            vec
            rotate
      end

      methods
            function obj = vec3d(a,b,c)
                  vec = [a,b,c];
                  rotate = rot(obj) ;
            end
      end
end

I have another class that is named rot; which has functions for rotating vectors. What i would like to do is:

MyVec = vec3d([1;2;3]);
MyVec2 = MyVec;

% Define a Directional cosine matrix to rotate the vector
MyDCM = ... ;

MyVec.rotate.byDCM(MyDCM) ;
% MyVec should now contain the rotated vector
% MyVec2 should remain as the original vector

If i use handle class instead of value class, i can do this manipulation; however if i set another variable equal to MyVec, they become linked (both point to the same object) which is what i want to avoid.

I would like to pass a pointer to my variable to the rot class, so that i can manipulate it within the functions of the rot class.

In short: I want to be able to use

MyVec.rotate.byDCM( MyDCM)

to modify MyVec, without actually creating a copy of it in the memory. I want byDCM to be a method within rotate, not that of MyVec. And i would like to be able to safely deep copy my variable.

I hope i explained myself clearly. Thank you for your time.

Upvotes: 2

Views: 330

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60780

You want to do

MyVec = rotate.byDCM(MyVec, MyDCM);

The only way to modify a variable passed into a function is if it is a handle class, but then you will not be able to make a deep copy with MyVec2 = MyVec.

If the rotate.byDCM function is implemented as follows:

function vec = byDCM(vec, DCM)
   % modify vec here

then MATLAB will optimize things so that vec is never copied. Note that in the function definition, the same variable name appears in the input and output list. When calling the function, the same variable (MyVec) that is passed as that argument also receives the output. The MATLAB interpreter understands this and allows the function to modify the variable in-place.

Reference: https://blogs.mathworks.com/loren/2007/03/22/in-place-operations-on-data/

Upvotes: 3

Related Questions