Multiple names for a single variable.

조회 수: 9 (최근 30일)
Joshua Arenson
Joshua Arenson 2021년 1월 27일
댓글: Walter Roberson 2021년 2월 15일
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