Multiple names for a single variable.

15 visualizaciones (últimos 30 días)
Joshua Arenson
Joshua Arenson el 27 de En. de 2021
Comentada: Walter Roberson el 15 de Feb. de 2021
Hi folks, I'm wondering if this is possible and how one would go about doing it.
I have a structure data. It has a field say, ActiveInd, so data.ActiveInd. I want to be able to have some kind of shorthanded name to keep the code easier to read and shorter, say AInd. Now I could (and have) code that says soemthing like:
AInd = data.ActiveInd
[do stuff to AInd]
data.ActiveInd = AInd.
Of course the doing stuff to AInd means I now have two variables, AInd and data.ActiveInd increasing memory usage. With tons of spare memory this isn't an issue but I'm starting to push up against memory caps. I'd love to able use both AInd and data.ActiveInd to point to and alter the same stuff in memory without using excess memory. Is this possible?

Respuestas (1)

James Tursa
James Tursa el 27 de En. de 2021
There are no "variable pointers" in MATLAB, so no generic alias capability as you would probably want. Other options to consider:
  • Use data.Activelnd spelled out in all your code, instead of an assigned copy
  • Use functions to modify data.Activelnd with special syntax that allows "in-place" modification
  • Use classdef objects derived from handle that would essentially allow the alias behavior you want
  13 comentarios
Jan
Jan el 15 de Feb. de 2021
@Walter Roberson: In my Win10/R2018b system, your code shows expected behavior: The element is set to 27 immediately. But I see this
format debug
data.ActiveInd = 1:3;
% data.ActiveInd % Uncommenting does not let the zeros disappear
data
data.ActiveInd
% Output:
data = struct with fields:
ActiveInd: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
ans =
Structure address = 100266a0
m = 1
n = 20
pr = ff92c9c0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
With data.ActiveInd=rand(1,3) this effect does not appear.
Walter Roberson
Walter Roberson el 15 de Feb. de 2021
The test I just did with R2020b on Mac has data display with field ActiveInd that is [8 8 8] -- right length but wrong content.

Iniciar sesión para comentar.

Categorías

Más información sobre Structures en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by