Question

Say I have a dynamically built struct (such as data.(casenames{c}).t25s). Accessing this dynamically quickly makes very cluttered and hard-to-read code with lots of duplication (e.g. plot(data.(casenames{c}).t14s.x,data.(casenames{c}).t14s.y);).

So my question is:

Can I pass a struct by reference to another variable?

Something like the following:

for cno = 1:length(casenames)
   data.(casenames{c}) = struct;
   ... % do some file reading and fill in .x and .y
end

for cno = 1:length(casenames)
   case = @data.(casenames{c}); % Naïve parse by ref
   case.z = case.x + case.y
end

This should then cause data.(casenames{c}).z to be assigned the value of data.(casenames{c}).x + data.(casenames{c}).y

Was it helpful?

Solution

With basic data types, no. You can get handles to objects, so if your structs and data methods are sufficiently complex, that may be worth a thought. Otherwise, it's usually possible to simply refactor the code for clarity:

for cno = 1:length(casenames)
   data.(casenames{c}) = struct;
   ... % do some file reading and fill in .x and .y
end

for cno = 1:length(casenames)
   % read-modify-write idiom
   data.(casenames{c}) = dosomething(data.(casenames{c}));
end

function case = dosomething(case)
   case.z = case.x + case.y;
end

Side note: since Matlab's "pass by value" is actually "pass by reference with copy-on-write" internally, it's possible to exploit this from MEX functions, but it's entirely unsupported and may cause unexpected behaviour.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top