无法将函数结果分配给数组索引

时间:2014-12-18 09:04:08

标签: arrays matlab indexing

我有一个名为simulate_ant()的函数,它在32x32网格上返回模拟蚂蚁的适应值,它将网格的文本文件和由30个数字组成的字符串作为参数,构成一个有限状态机器,10个状态,每个由3位数字代表。

我创建了一个包含30个数字字符串的数组,我想迭代10次,并用函数的结果填充一个单独的数组,为此我编写了这段代码:

% our first generation of ants
first_gen = ['110202132224154246176368198100';'110202132224154246176368198100';'110202132224154246176368198100';'110202132224154246176368198100';'110202132224154246176368198100';'110202132224154246176368198100';'110202132224154246176368198100';'110202132224154246176368198100';'110202132224154246176368198100';'110202132224154246176368198100'];
first_gen_fitness = [0,0,0,0,0,0,0,0,0,0];

% get fitnesses of first generation of ants
for i = 1:10

    first_gen_fitness(i) = simulate_ant('muir_world.txt', first_gen(i));

end

我期望的是first_gen_fitness可以填充10 47个像这样:first_gen_fitness = [47, 47, 47, 47, 47, 47, 47, 47, 47, 47];但是它只是出现了10 0。

有人可以告诉我哪里出错了吗?

1 个答案:

答案 0 :(得分:3)

原因是:

first_gen(1) == '1',而不是'110202132224154246176368198100'

你可以这样做:

first_gen(i,:)

获取整个第一行。所以总的来说:

% our first generation of ants
first_gen = ['110202132224154246176368198100';'110202132224154246176368198100';'110202132224154246176368198100';'110202132224154246176368198100';'110202132224154246176368198100';'110202132224154246176368198100';'110202132224154246176368198100';'110202132224154246176368198100';'110202132224154246176368198100';'110202132224154246176368198100'];
first_gen_fitness = zeros(10,1)

% get fitnesses of first generation of ants
for ii = 1:10
    first_gen_fitness(ii) = simulate_ant('muir_world.txt', first_gen(i,:));
end