how can I generate matrix from each cell array and then separately apply matrix operation on each matrix?
Show older comments
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?
Accepted Answer
More Answers (1)
Guillaume
on 9 Jan 2017
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]);
Categories
Find more on Genetic Algorithm in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!