Do "pointers" exist in MATLAB? A question about the efficiency of using shorthands.

37 views (last 30 days)
I'm not sure I'm using the right vocabulary, but here's what I mean.
Say I have data in this structure:
input.a.b.c.verylongname.thisistoolong.itmakesthecodehardtoread
This data will not be modified in the code I'm writing.
Say I create a shorthand:
muchsmaller = input.a.b.c.verylongname.thisistoolong.itmakesthecodehardtoread
and use that shorthand to access the data throughout the code.
Now, say that data is big. Will MATLAB actually create a copy of the data, using up memory, or will it use what I believe is called a "pointer" and simple point towards the same data regardless of the variable name I use?
Thank you!

Accepted Answer

the cyclist
the cyclist on 4 Feb 2023
Edited: the cyclist on 4 Feb 2023
In general, MATLAB will not allocate new memory until it needs to, and will just use the same "array reference" to memory. See How MATLAB Allocates Memory for details.
That page does not specifically mention the case of copying from a structure to a numeric array, but I did a bit of testing, and confirmed that there is not an increase in memory use.
  1 Comment
James Tursa
James Tursa on 4 Feb 2023
@Patrick Aoun The caveat here is that this doesn't behave like a pointer in C/C++. As long as you don't change the underlying data (as you state) things will behave as you expect. But if you change the underlying data, then a deep data copy will occur and your shorthand named variable will be disconnected from the structure variable from that point on.

Sign in to comment.

More Answers (0)

Tags

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!