Matlab Arrays not populating correctly

2 ビュー (過去 30 日間)
Cathal White
Cathal White 2020 年 11 月 4 日
編集済み: Cris LaPierre 2020 年 11 月 4 日
Hi all, I'm getting a problem with MATLAB where the values being inserted into a vector are appearing as [] instead of [rand, 0].
This is my code:
M = 10; %no of chromosomes (candidate solutions)
N = 2; %no of genes
for k = 1 : M
population.Chromosomes(M).Gene(:) = [rand, 0];
population.Chromosomes(k).fitness = fitnessFunction(population.Chromosomes(M).Gene(:) );
end
The matrix population.Chromosomes should show all the values in the gene column as [0.8344,0] for example, and I'm sure these cells have values as the fitness vector has a value.

採用された回答

Cris LaPierre
Cris LaPierre 2020 年 11 月 4 日
編集済み: Cris LaPierre 2020 年 11 月 4 日
Your code is telling it to assign [rand,0] to gene(M). This means that it will always assign the value to the 10th row, which is what it looks like it is doing. You are assigning correctly for fitness, and you can see the values of Gene change each time since the values for fitness are different in every row.
Did you mean to use k instead?
M = 10; %no of chromosomes (candidate solutions)
for k = 1 : M
population.Chromosomes(k).Gene = [rand, 0];
end
And now to visualize the results.
population.Chromosomes.Gene
ans = 1×2
0.8894 0
ans = 1×2
0.4122 0
ans = 1×2
0.4319 0
ans = 1×2
0.8130 0
ans = 1×2
0.4936 0
ans = 1×2
0.8817 0
ans = 1×2
0.8535 0
ans = 1×2
0.0575 0
ans = 1×2
0.7653 0
ans = 1×2
0.5670 0
  1 件のコメント
Cathal White
Cathal White 2020 年 11 月 4 日
Thank you.

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

その他の回答 (1 件)

dpb
dpb 2020 年 11 月 4 日
You've got a typo...
population.Chromosomes(M).Gene(:) = [rand, 0];
is writing into the location M(=10) every time.
  1 件のコメント
Cathal White
Cathal White 2020 年 11 月 4 日
Thank you.

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

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by