Addressing nested fields in a function with struct variable
显示 更早的评论
Hi,
Would like some advice on how to accomplish the following. This may not be the best way, so I would also appreciate any comment on a more efficient way to do it.
I am passing to a function a struct, which contains nested arrays. In this case I am trying to address the FaceColor field.
This field is stored in figure > UserData > Patch > FaceColor. UserData is a 1×2 struct array with fields: Name Data DatadB Patch
I have passed the arguments as a struct. The code works in Matlab, however it creates a new variable 'var' in f1.UserData.
Edit: Clarified code snippets.
%This is fed as 'var' into function updateColor
struct('src', lstIsoSelectSubHnd, 'srcProp', 'Value', 'dst', f1, 'dstProp1', 'UserData', 'dstProp2', 'Patch.FaceColor')
function updateColor(src, var)
src.BackgroundColor = uisetcolor([0 0 0], 'Isosurface Color');
numIndex = var.src.(var.srcProp); %Check List to see which Iso to color
var.dst.(var.dstProp1)(numIndex).var.dstProp2 = src.BackgroundColor;
end
2 个评论
Nicholas Tiong
2018-1-15
Walter Roberson
2018-1-15
"But I don't quite understand why I can't pass two fields with a period in between such as dstProp2 = 'Patch.FaceColor'."
Because any one dynamic field name might be naming a non-scalar struct and they did want to have to define the meaning for the combination of multiple field names and non-scalars.
回答(1 个)
Walter Roberson
2018-1-15
That code cannot work in MATLAB.
Although you have a ... continuation on the first line, you have matched brackets on the struct() call so the comma on the first line marks the end of an expression whose value is to be printed. The ... then indicates that the second expression is continued on the next line. So the second line must be an independent expression that can be considered without the first one; the struct() call was made but had no assignment so the struct() was discarded.
Now on the second line you have
(var.dst.(var.dstProp1))(numIndex)var.dstProp2
on the left side of an assignment. Match brackets and you see that
(var.dst.(var.dstProp1))
is a subexpression that is followed by () indexing. But in MATLAB it is not legal to follow a () expression by indexing of any kind. If it were legal, then (var.dst.(var.dstProp1))(numIndex) would be an indexed variable and in MATLAB it is not legal to follow an indexed variable by a variable name.
I cannot tell what you are trying to do here.
类别
在 帮助中心 和 File Exchange 中查找有关 Whos 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!