MATLAB Answers


How to replace an element in an struct array

Asked by tevzia
on 21 Aug 2013


I have a problem about replacing an element in the array with a new one.

Could you please take a look and tell me what i'm doing wrong?

 breedpop = 
1x100 struct array with fields:
    % every array has 10 element in it.

I tried to replace one of the element in the breedpop.penalty array(doesnt matter index of the element) this way

breedpop(i).penalty = newgeneration(i).penalty;

It works if i run once but when i run it more than 100(number of iteration) bredpop.penalty becomes more than 10 element.

How can I do it?

  1 Comment

We would need to see more about how you create newgeneration(i).penalty


No products are associated with this question.

1 Answer

Answer by Azzi Abdelmalek
on 21 Aug 2013
Edited by Azzi Abdelmalek
on 21 Aug 2013
 Accepted answer

Because newgeneration(i).penalty when i >100 contains more then 10 elements

If you want to take the first 10 elements

breedpop(i).penalty(1:10) = newgeneration(i).penalty(1:10);


on 21 Aug 2013

I wanna replace one from the list(newpopulation.penalty) to old list (breedpop.penalty)

breedpop(i).penalty = newgeneration(i).penalty(end) 

however it didn't work

on 21 Aug 2013

I solve it. thank you

breedpop(n).penalty = newpopulation(i).penalty(end)

n is the last one of the list (number of the elements)

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!