Borrar filtros
Borrar filtros

Error using a structure array in a for loop.

2 visualizaciones (últimos 30 días)
Yro
Yro el 25 de Mayo de 2021
Editada: Yro el 25 de Mayo de 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.

Respuestas (1)

Walter Roberson
Walter Roberson el 25 de Mayo de 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 comentario
Yro
Yro el 25 de Mayo de 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.

Iniciar sesión para comentar.

Categorías

Más información sobre Structures en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by