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
0 件のコメント
採用された回答
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;
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!