Error using a structure array in a for loop.
2 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Walter Roberson
on 25 May 2021
[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 .
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!