Use of pointers to structures

49 views (last 30 days)
Ricardo
Ricardo on 9 Dec 2014
Edited: Matt J on 9 Dec 2014
Dear all,
I would like to know if it is possible to use pointers to structures. The case I would like to use this time is like this:
% case_tal,case_cual are structs with data from different systems, I want to loop on them
for i_case = [case_tal,case_cual]
% i_case.file is an array of files that I want to loop within each case
for i_file = i_case.file
i_file.data = do_stuff_on_the_data;
end
end
I want to use pointers because I would like that when I do
i_file.data = do_stuff_on_the_data;
the struct really is modified and store the data, not lose it.
Is it possible?
Thanks in advance!

Answers (2)

Adam
Adam on 9 Dec 2014
Edited: Adam on 9 Dec 2014
Matlab does not have the concept of pointers.
You can use a class derived from handle to achieve this 'by reference' behaviour instead of a struct, but a struct in Matlab is just a simple object to hang data off and you have to reassign to the struct if you want to change the data.
You can just do:
i_file.data = do_stuff_on_the_data( i_file.data );
though. It's ugly as a programming construct, but it does the job when you can't pass things by reference (or pointer).
Document for reference on classes if you aren't aware of it:

Matt J
Matt J on 9 Dec 2014
Edited: Matt J on 9 Dec 2014
The simplest solution would be to simply return i_file as an output from whatever function is performing the code you show. However, to have the semantics you mention, you could create a handle class
classdef myclass<handle
properties
data
end
end
Now, when you create the variable as follows
i_file=myclass;
it will have the behavior you're looking for.

Categories

Find more on Structures in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!