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.

回答(1 个)

Walter Roberson
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 .
  1 个评论
Yro
Yro 2021-5-25
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by