Error using a structure array in a for loop.
2 次查看(过去 30 天)
显示 更早的评论
Hello,
When I use the structure array ('new_popc.Position') in a loop I get the following error after the second iteration:
'Scalar structure required for this assignment.'
'Error in TEST (line 19)'
'new_popc.Position = repmat(empty_individual, length(pop_unique), 2);'
This is the code:
count = 0;
for k = 1:5
pop_unique = zeros(100, 2);
count = count + 1
% RESHAPE POPULATION
for i = 1:100
pop_unique(i,:) = out.pop(i).Position;
end
[pop_unique, ia, ic] = unique(pop_unique, 'first','rows');
%% CREATE A NEW STRUCTURE WITH THE NEW ARRAY
empty_individual = [];
new_popc.Position = repmat(empty_individual, length(pop_unique), 2);
for j = 1:length(pop_unique)
new_popc(j).Position = pop_unique(j,:);
end
[out.pop.Position] = new_popc.Position;
end
I think it must be to when I update the structure array. How can I fix this error?
Thanks in advance.
0 个评论
回答(1 个)
Walter Roberson
2021-5-25
[out.pop.Position] = new_popc.Position;
That is an error if out is a non-scalar struct. If out is a non-scalar struct then out.pop would be struct expansion, and when you use struct expansion you cannot use a substructure reference in the assignment.
Be careful, the right hand side involves the non-scalar struct new_popc so new_popc.position generates multiple outputs.
If out did not exist before the assignment, or if it were a scalar struct that did not have a field named pop, or if it were a scalar struct with a non-scalar struct the same number of elements as new_popc, then in any of those three cases, the assignment you wrote would be valid, and would copy the position information from new_popc to out.pop .
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!