## Trying to generate a value each loop, and then add that value to multiple variables in an array

Stephen

### Stephen (view profile)

さんによって質問されました 2019 年 3 月 14 日

### Stephen (view profile)

さんによって コメントされました 2019 年 3 月 14 日
Jan

### Jan (view profile)

さんの 回答が採用されました
Hello,
Say I have an array with 2 variables, LPCopen and HPCopen.
I would like to create a loop that each generation will add the same new figure 'cyclesnew' to both 'LPCopen' and 'HPCopen'. I would like to store all generations in a matrix for reference elsewhere.
The end result, would be something like;
[LPCopen+cyclesnew(1), HPCopen+cyclesnew(1)]
[LPCopen+cyclesnew(2), HPCopen+cyclesnew(2)]
.....
and so on
Can anyone advise on the most efficient way to do this? It will need to be expanded to adding the cyclesnew(i) value to about 6 variable in an array. Bad code below for reference. Thanks!
for i = 1:100
cyclesnew(i) = randi(20000);
stack(i) = [LPCopen+cyclesnew(i),HPCopen+cyclesnew(i)];
population = [population ; stack(i)];
i= i+1;
disp(population)
format long g
end

#### 0 件のコメント

サインイン to comment.

R2018b

## 1 件の回答

### Jan (view profile)

2019 年 3 月 14 日
採用された回答

for i = 1:100
i= i+1;
end
You do not have to increase the loop counter manually inside a for loop. This is done by for already.
Defining format long g inside the loop is a waste of time, but no error. For a proper programming style, do this once before the loop.
stack(i) = [LPCopen+cyclesnew(i),HPCopen+cyclesnew(i)];
There is a scalar on the left side and a [1 x 2] vector on the right side. This does not work.
format long g
for i = 1:100
cyclesnew(i) = randi(20000);
population = [population ; LPCopen+cyclesnew(i),HPCopen+cyclesnew(i)];
disp(population)
end
This displays a [1 x 2] vector in the first iteration, a [2 x 2] matrix in the second one and so on. Finally you write [sum(1:100) x 2] values to the command window: 2020 numbers. This is not useful.
And easier approach does not need loops at all:
format long g
cyclesnew = randi(20000, 100, 1);
population = [LPCopen, HPCopen] + cyclesnew;

Stephen

### Stephen (view profile)

2019 年 3 月 14 日
Hi Jan,
Thanks for the answer, I knew it was gonna be simpler but I didnt know how simple haha
If you dont mind answering a follow up, the end goal here is to have each generation of the population accessible for use, the code overall will function as a (kind of) genetic algorithm. Accessing each row the population and mixing/mutating values between them should be possible.