How can I vectorize copying one struct to another?

I have
p.Results.events(i)
ans =
struct with fields:
message: {16×1 cell}
time: [16×1 uint32]
and
obj.data{1}
ans =
1×70 struct array with fields:
gx
gy
time
events
where for example
obj.data{1}(1).gx(1:10)
ans =
532.4000 532.3000 532.2000 531.8000 531.1000 530.2000 528.9000 527.6000 527.3000 527.9000
I was able to do this using
[obj.data{1}.gx] = p.Results.x{:};
[obj.data{1}.gy] = p.Results.y{:};
[obj.data{1}.time] = p.Results.time{:};
for i = 1:70
obj.data{1}(i).events = p.Results.events(i);
end
It seems like in theory, copying the struct should be the easiest to vectorize but I've hit a wall. If it helps, I know exactly what the fields of events should be.
the source code is on github in the constructor

 采纳的回答

events = num2cell(p.Results.events); %convert array to cell array so that it can then be converted to comma separated list
[obj.data{1}.events] = events{:}; %expand cell array into comma separated list and deal into outputs
However, your hierarchy of non-scalar structure within a cell array within a structure can easily be confusing to the reader of your code. You may want to simplify that a bit.

5 个评论

Ah have to convert it, thank you!
And I wish I could simplify, unfortunately I have to make my data a certain shape to work with existing scrips.
Follow up question,
what would you recomend for
for i=1:obj.num_trials
obj.data{1}(i).num_samples = length(obj.data{1}(i).gx);
end
considering that each vector has a different length?
The for loop is probably the fastest. Another option would be:
l = cellfun('length', {obj.data{1}.gx}, 'UniformOutput', false); %force cell output
[obj.data{1}.num_samples] = l{:};
But cellfun is just a loop in disguise. Note that the cellfun('length', ...) syntax is deprecated and the modern way of doing the same would be:
l = cellfun(@numel, {obj.data{1}.gx}, 'UniformOutput', false);
which will be even slower.
makes sense, thank you for the replies
@Guillaume, could you please explain more elaborately why do you need to convert the array of a field into a cell array, and then put the target field into square brackets?

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by