I have a relatively simple problem that my Google-fu hasn't managed to solve that I think must have a solution.
I have a m-by-n array of values, and I am trying to assign them to fields in a m-by-n structure. This is trivial using a for loop (shown below), I am just wondering there a better/more efficient way of doing it.
values = rand(4,8);
for i = 1:4
for j = 1:8
val_struct(i,j).a = values(i,j);
end
end
Since I need to do this for a lot of fields, I am a bit reluctant to just run through a bunch of for loops if I don't absolutely need to.
You can use num2cell
and struct
:
val_struct = struct('a', num2cell(values));
Note that numeric arrays are much more efficient than struct arrays
.