MATLAB: Access to array of structs (no for loops)

array of structsMATLAB

Dear All,
From an array of structs I want to access all last elements of field datarow using one command.
Construct the array of structs:
%init struct
rec.datarow = [1,2,3,4,5];
rec.datacol = [1,2,3,4,5]';
rec.name = 'apple';
%init array of structs
rec(2:3) = rec;
Access fields name, datarow, datacol and last element of datarow of first struct. No problem here.
%get field name of all structs in once using comma-separated lists
allnames = {rec.name}
%get field datarow of all structs in once using comma-separated lists
alldatarow = [rec.datarow]
%get field datacol of all structs in once using comma-separated lists
alldatacol = [rec.datacol]
%get end value of field datarow of first struct
v1 = rec(1).datarow(end)
It appear to be sensible to store data in column format because the collection in comma separated lists yields in a handy matrix.
Now my question: Is there a way to access all end values of datarow with one command (no for loops or temporary variables)?
I was expecting that the following command should work:
%but how to get the end values of datarow of all structs in once??
allendvalues = [rec.datarow(end)]
But I get this error: Expected one output from a curly brace or dot indexing expression, but there were 3 results
Anyone some ideas?
Patrick

Best Answer

"Is there a way to access all end values of datarow with one command (no for loops or temporary variables)?"
Nope.
"Anyone some ideas?"
You could hide the loop inside a cellfun or an arrayfun call (but an explicit loop is usually more efficient):
>> arrayfun(@(s)s.datarow(end),rec)
ans =
5 5 5
The cause of that error message is explained here:
You can learn about comma-separated lists here: