Assigning different data types to struct arrays using comma separated list assignment. Are there better options?

17 views (last 30 days)
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
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
Benedikt
Benedikt on 29 Oct 2025
Thanks to both of you (@Matt J and @Stephen23)!
In my actual application code the switch from loops to this kind of assignment was much more performant (factor 10 or more). However, based on both of your comments I realize, that the reason for the increase in performance might be that I had to vectorize as described in to make this possible:
I consider this question fully answered. I learned a lot. Thank you for your help!
Rik
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:
  1. 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)
  2. cellfun with the legacy input (although be careful with 'isempty' and 'prodofsize')
  3. for/while loops
  4. cellfun/arrayfun/structfun/etc (these are just hiding an internal loop)

Sign in to comment.

More Answers (0)

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!