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

1 view (last 30 days)
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

Accepted Answer

Jan
Jan on 14 Mar 2019
Your code contains several problems:
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;
  1 Comment
Stephen
Stephen on 14 Mar 2019
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.
Would that be possible with the output of your answer?
Thanks again

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!