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

3 ビュー (過去 30 日間)
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

採用された回答

Jan
Jan 2019 年 3 月 14 日
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 件のコメント
Stephen
Stephen 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.
Would that be possible with the output of your answer?
Thanks again

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by