Anonymous Function : asymmetric read/write behaviour
Mostrar comentarios más antiguos
I'm trying to use function handles to create an equivalent to a "with" statement in VBA or a alias in Python but I find myself facing a behaviour I don't understand. maybe some of you could help me understand why I get an error.
Boiled down to the simplest, here's what I get:
a=@(x)x{1};
y={10};
a(y)
try a(y)=100
catch ME
ME
end
The reading part works well but the next line results in an error. Why is there an asymmetry while evaluating the parentasis?
EDIT :
The most efficient to create a VBA:with or Python:alias equivalent in Matlab I found is to do an actual copy of a structure subpart, make modifications and reassign the edited branch copy to its original structure as:
S=struct();
S.Branch0 = "Just Some Data";
S.Branch1=struct();
for i=1:10
% Setting up preexisting values in the structure
for j=1:10
S.Branch1(i).NotCopiedProperty{j} = i;
end
S.Branch1(i).CopiedProperty = 10:-1:1;
% Create a phantom copy of the whole branch
with = S.Branch1;
% Add properties to the phantom branch
with(i).NewProperty1='Some Text';
with(i).NewProperty2={'A1','A2'};
% Create a copy of the original data and the edit it
with(i).CopiedProperty(i) = 0;
% Overwrite the original subBranch with the phantom branch
S.Branch1=with;
end
disp(S)
disp(S.Branch1)
Limitations : If new fields are to be added in a loop, the "with" structure must capture all instances at looping level.
% DOES NOT WORK
with = S.Branch1(1); % Points to ELEMENT
with.NewProperty1='New Text';
S.Branch1(1)=with;
% DO INSTEAD :
with = S.Branch1; % Points to ARRAY
with(i).NewProperty1='New Text';
S.Branch1=with;
% STILL WORKS
with = S.Branch1(1);
with.ExistingProperty1='Replacement Text';
S.Branch1(1)=with;
2 comentarios
Steven Lord
el 8 de Nov. de 2023
What exactly are you hoping to do with that last line? If a(y) returned 10 on both sides, what would you expect this command to do in MATLAB?
10 = 100
Walter Roberson
el 8 de Nov. de 2023
They are trying to create an alias. So they would like a(y) to be an alias for y{1} including for assignment purposes. They would like a(y)=100 to act the same as y{1} = 100
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Matrix Indexing en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!