Accessing struct variable using another variable.

1 view (last 30 days)
Hi, I will like to use another a variable to modify another variable like a pointer in C programming.
distance.rate = 10;
a = distance.rate.rate;
distance.rate.rate = 20;
a is still 10 but I want to make "a" link to "distance.rate.rate" is it possible?
I have many variable with really long name so it will be helpful to refer to it using a few letters.

Answers (1)

Arjun
Arjun on 9 Aug 2024
Hi,
As per my understanding, you want to enable functionality such as pointers for your application but MATLAB does not provide such a feature. We can make it work but with some modification. When you do the following:
person = struct('name', 'John Doe', 'age', 21, 'scores', [90, 85, 88]);
person2 = person;
person.name = 'Kevin';
MATLAB will create a new variable person2 and will copy all the values from person to person2 and from then onwards they will be two separate entities and hence changing person.name to ‘Kevin’ won’t modify the field under person2.
We can do some modification to achieve what we decide by making a class which inherits from handle in MATLAB and then defining struct as a property of the class. Here is how it is done:
%Make a class file
classdef dummy<handle
properties
person = struct('name', 'John Doe', 'age', 21, 'scores', [90, 85, 88]);
end
end
%In the main file instantiate and use
Person1 = dummy;
Person2 = Person1;
%Change some property of Person1
Person1.person.name = 'Kevin';
disp(Person2.person.name);
%You will see that it displays Kevin, hence we achieved the desired behaviour
I am attaching the documentation for the handle class in MATLAB:
I hope this will help!

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!