Applying functions and assignments on multiple struct fields with only one command
Show older comments
I have this problem very often and want to give just one example. But I want to find - if possible - a more general solution to the problem, not to this specific example. Try the following code:
figure
plot(rand(5,3)) % will plot 3 random lines with three different colors
a = gca;
a.Children(2).Color = rgb2gray(a.Children(2).Color); % will convert the color of the 2nd line (orange with the default color scheme in 2016a) to grayscale
But if I want to apply a function on all fields of Children(:).Color and overwrite the original values in all fields of Children(:).Color with just one command, I will fail, e.g.:
a.Children(:).Color = rgb2gray(a.Children(:).Color); % intention: convert all Colors to Gray and overwrite the original colors with one single assignment...
Error using rgb2gray
Too many input arguments.
The error that occured in this case was obviously already due to the wrong input for rgb2gray on the right side of the assignment (this is a side problem, see later), but even when using (just as example...)
a.Children(:).Color = a.Children(:).Color;
Expected one output from a curly brace or dot indexing expression, but there were 3 results.
there will be an error.
Is there a way how to get such multiple struct assignments solved in a comprehensible way with only one simple command (no for loops, which are so annoying and code space consuming...), which can also be realised when the case is a little bit different... - a general solution, if you want to call it like this? Do you have any other hints for related problems with such (nested?) structs (with complex substructs and so on...)?
Side problem: rgb2gray expected a N x 3 matrix as input. a.Children(:).Color is basically also N x 3 (each Color is 1x3 nested within a length(a.Children) struct), but unfortunately it is contained in a nested struct, so that one has to use a command like this
rgb2gray(reshape([a.Children(:).Color],length(a.Children),3))
to get a N x 3 (length(a.Children) x 3 actually) array from the struct. Is there a simpler command that just converts a nested struct like this (e.g. the Color field of Children(1) to Children(N)) with one simple command to a similar matrix with size(Children) x size(Color)? For example: if 'Children' was a [3x5] struct and 'Color' a [7x6] Matrix, a command that creates a [3x5x7x6] array from it, instead of a confusing [7x(6x3x5)] = [7x90] array, which the square brackets would do (in this example), making it hard to understand how the array must be reshaped if one wants the original structure size back...].
Best regards and thanks,
usr0815
Accepted Answer
More Answers (0)
Categories
Find more on Structures in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!