我在MATLAB中有一个程序。我想运行该程序10,000次。对于每次运行,我得到最终输出作为计数。我想要的是将每次迭代的计数值导出到全局数组或excel电子表格。我想最后检查应该包含10,000个值的count数组。
请大家帮我们建议一下。我也在发布代码。
%%steps
%1.Initialize the populations
tic
clc; clear all; close all;
par_size=10;
%Encode
for i=1:par_size
par(i,:)=dec2bin(round(1+31*rand),10);
a(i) = bin2dec(par(i,:));
end
orig_par=par;
fitness = zeros(1,par_size);
count=0;
while sum(fitness)~=1000
count=count+1;
%%
%2.Evaluate fitness
fitness = zeros(1,par_size);
%The fitness function
%count the no of one's in the string
fitness = [(sum(par=='1',2)).*(sum(par=='1',2))].';
sum_fitness = sum(fitness)
prob_fitness = fitness./sum_fitness;
[~,I]=sort(prob_fitness);
%I is the order of the fitness value
prob_fitness_sort = prob_fitness(I);
%sorting
par = par(I,:);
%%
%3.Select Parents
%Roulette wheel selection
%generate cumulative probability
cum_prob = zeros(size(prob_fitness));
A = zeros(size(prob_fitness));
for i=1:par_size
A(i) = prob_fitness_sort(i);
cum_prob(i) = sum(A);
end
new_pop = par;
%Selection being done
r1 = zeros(1,par_size);
for i=1:par_size
r1(i) = rand;
if r1(i)<=cum_prob(1)
new_pop(i,:) = par(1,:);
elseif r1(i)>cum_prob(1) && r1(i)<=cum_prob(2)
new_pop(i,:) = par(2,:);
elseif r1(i)>cum_prob(2) && r1(i)<=cum_prob(3)
new_pop(i,:) = par(3,:);
elseif r1(i)>cum_prob(3) && r1(i)<=cum_prob(4)
new_pop(i,:) = par(4,:);
elseif r1(i)>cum_prob(4) && r1(i)<=cum_prob(5)
new_pop(i,:) = par(5,:);
elseif r1(i)>cum_prob(5) && r1(i)<=cum_prob(6)
new_pop(i,:) = par(6,:);
elseif r1(i)>cum_prob(6) && r1(i)<=cum_prob(7)
new_pop(i,:) = par(7,:);
elseif r1(i)>cum_prob(7) && r1(i)<=cum_prob(8)
new_pop(i,:) = par(8,:);
elseif r1(i)>cum_prob(8) && r1(i)<=cum_prob(9)
new_pop(i,:) = par(9,:);
elseif r1(i)>cum_prob(9) && r1(i)<=cum_prob(10)
new_pop(i,:) = par(10,:);
end
end
%new_pop is the new particle sample
%%
%4.Crossover and Mutate
%crossover
pc = 0.6; %pc is the crossover probability
for i=1:2:par_size %selecting adjacent couples
r2 = rand;
if r2<=pc
l = size(new_pop, 2);
%choose the parents
%here adjacent parents are taken
breeders(1,:)=new_pop(i,:);
breeders(2,:)=new_pop(i+1,:);
%choose a crossover point
cp = randperm(l, 1);
%do crossover
b1 = [breeders(1, 1:cp), breeders(2, cp+1:end)];
b2 = [breeders(2, 1:cp), breeders(1, cp+1:end)];
new_pop(i,:) = b1;
new_pop(i+1,:) = b2;
end
end
%mutation
%pm be mutation probability
pm = 0.01;
for i=1:par_size
r2 = rand;
if r2<=pm %mutation probability is 0.1
%Do mutation
%select random position
r3 = 1+round((10-1)*rand);
new_pop(i,r3)=num2str(abs(str2num(new_pop(i,r3))-1));
end
end
par = new_pop;
end
orig_par
par
count
toc
不要担心程序成功运行。如您所见,在计划的每次运行结束时都会显示作为计数生成的值。我想在可能的情况下将此值导出到全局数组或MATLAB中的Excel电子表格。
提前致谢。
对于任何查询都要做评论!
答案 0 :(得分:0)
您可以创建变量count_nb
并将其初始化为zeros(10000,1)
,并在while循环内(count = count + 1
之后)count_nb(count) = count
。在while
循环之外,您可以使用count_nb
将变量xlswrite
写入Excel,或将其保存到MAT文件,或将其写入文本文件等...... < / p>