How to assign a struct array to a field of another struct array?
显示 更早的评论
Hello everybody, thanks in advance for your help with this!
So I'm trying to assign a struct array to a field of another struct array when both have the same size and obviously trying to avoid a for loop.
It looks something like this
data % This is a struct array that doesnt have the field trait yet
trait % this is a struct array of the same length of data
assert(length(data) == length(trait))
data.t = trait % this fails with --> Scalar structure required for this assignment.
[data.t] = [trait] % this fails with --> Insufficient number of outputs from right hand side of equal sign to satisfy assignment.
[data.t] = [trait] % this fails with --> Insufficient number of outputs from right hand side of equal sign to satisfy assignment.
[data.t] = deal(trait) % works but assigns the whole trait struct array to the field t in each element of data
Im pretty sure that if trait was a cell where each element of the cell was each of the elements in the struct array then this should work
[data.t] = cellTrain{:}
But I cant figure out a way to expand the trait struct-array into a cell as struct2cell expands every field in every struct of the struct array into cells.
Finally for completion the result should be equivalent to this simple for loop but hopefully a bit more efficient
for i = 1:length(data)
data(i).t = trait(i);
end
Thanks once again for all the help!
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!