how can I generate matrix from each cell array and then separately apply matrix operation on each matrix?
조회 수: 2 (최근 30일)
이전 댓글 표시
I have coded a population generation stage in genetic algorithm
npop=10;
Vmin=1;
Vmax=3;
nVar=Types_Machine;
VarSize=[1 nVar];
%initial Population
for i=1:npop
pop{i}=randi([Vmin,Vmax],VarSize)
end
then using the following code I can convert the array into matrix
R=1:numel(pop{i})
Z = zeros(R(end),max(pop{i}))
Z(sub2ind(size(Z),R,pop{i})) = 1
end
if one array is [1 1 2 3 1 2 1] the matrix z seems like
z=[1 0 0
1 0 0
0 1 0
0 0 1
1 0 0
0 1 0
1 0 0]
but this is giving an error I want to generate an array with all the matrices generated from pop{i}.I tried combining both in this way
npop=10;
Vmin=1;
Vmax=3;
nVar=Types_Machine;
VarSize=[1 nVar];
%initial Population
for i=1:npop
pop{i}=randi([Vmin,Vmax],VarSize)
end
[r4,c4]=size(pop)
for i=1:c4
R=1:numel(pop{i})
Z = zeros(R(end),max(pop{i}))
Z(sub2ind(size(Z),R,pop{i})) = 1
end
but result is separate matrices. how to combine all?
댓글 수: 0
채택된 답변
Stephen23
2017년 1월 9일
편집: Stephen23
2017년 1월 9일
Just like you use with pop, you can put those numeric arrays into one cell array (untested as you did not provide us with Types_Machine):
npop = 10;
Vmin = 1;
Vmax = 3;
nVar = Types_Machine;
VarSize = [1,nVar];
%initial Population
pop = cell(1,npop);
for k = 1:npop
pop{k} = randi([Vmin, Vmax], VarSize);
end
[r4, c4] = size(pop)
out = cell(1,c4)
for k = 1:c4
R = 1:numel(pop{k});
Z = zeros(R(end), max(pop{k}));
Z(sub2ind(size(Z), R, pop{k})) = 1;
out{k} = Z;
end
Or put all of the data into one 3D array, as Guillaume shows.
추가 답변 (1개)
Guillaume
2017년 1월 9일
If you're trying to generate a 3D array, I would do it like this:
pop = randi([Vmin, Vmax], [npop, nVar]);
Z = zeros(npop, Vmax, nVar);
Z(sub2ind(size(Z), repmat(1:npop, 1, nVar), reshape(pop, 1, []), repelem(1:nVar, npop))) = 1;
Or:
pop = randi([Vmin, Vmax], [npop, nVar]);
Z = permute(reshape(fliplr(dec2bin(2.^(pop-1), Vmax) - '0').', Vmax, npop, nVar), [2 1 3]);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Genetic Algorithm에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!