Error using a structure array in a for loop.

2 views (last 30 days)
Yro
Yro on 25 May 2021
Edited: Yro on 25 May 2021
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.

Answers (1)

Walter Roberson
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 .
  1 Comment
Yro
Yro on 25 May 2021
Thanks for your comments.
The problem is from iteration 1 when the array already exists, for this first iteration if it works what I want to do. What I am doing is to eliminate the repeated values of the array out.pop.Position, for with the unique function, I create the array new_pop.Position and then with this array I update out.pop.Position. But this only works for the first iteration, and in the second it does not work because the array new_pop.Position exists. How could I update this array to not get this error, or some other way to assign the pop_unique array to out.pop.Position.

Sign in to comment.

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!