Multiple names for a single variable.

9 次查看(过去 30 天)
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?

回答(1 个)

James Tursa
James Tursa 2021-1-27
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 个评论
Jan
Jan 2021-2-15
@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 2021-2-15
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by