Assigning different data types to struct arrays using comma separated list assignment. Are there better options?
17 views (last 30 days)
Show older comments
Hi,
To prevent for loops for assigning values in struct arrays I often use comma separated list assignement, like this:
valueVector; % some kind of 1D matrix, which contains, what I want to assing
logIdx; % logical array to assign values
% convert it to a cell array
cnvCell = num2cell(valueVector);
% assign it to the struct array
[structArr(logIdx).mySpecialField] = cnvCell{:};
I like the performance of the code, however, I find it more difficult to read than for-loops. Is there a more elegant way to do a comma separated list assignement?
Accepted Answer
Matt J
on 25 Oct 2025
Edited: Matt J
on 25 Oct 2025
I like the performance of the code, however, I find it more difficult to read than for-loops
Why not just use for-loops then, if they look better to you? num2cell is no faster.
8 Comments
Rik
on 29 Oct 2025
Just a further bit of context: vectorized code in Matlab is generally faster because it forced you to write good code. There can also be an inherent advantage for functions that operate on an entire array at once. If such functions don't exist, a loop will be fast. It used to be true that for-loops resulted in less performant code, but that hasn't really been true since 2 decades (2007b had a big jump IIRC, don't quote me on that, that was well before I even started using Matlab).
The order of performance is usually:
- Vectorized functions (e.g. using mean on an array instead of looping over the elements to compute a sum and dividing by the element count)
- cellfun with the legacy input (although be careful with 'isempty' and 'prodofsize')
- for/while loops
- cellfun/arrayfun/structfun/etc (these are just hiding an internal loop)
More Answers (0)
See Also
Categories
Find more on Data Type Identification in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!