Each matrix of the of the cell should be unique/different from each other
1 view (last 30 days)
Show older comments
I am new to matlab. I have to create a cell in which each matrix is different from the earlier cell entries. Hence i am writng the code such that each matrix is checked before it is stored in cell with all previous matrix in the cell. That means, W{4} would be stored in the cell only if W{1},W{2},W{3} are different from W{4}. Can anyone help ? Thanks in advance.
clc;
clear all;
n = 2;
W=cell(5,1);% Different Matrix
i=1;% initialization
while i<6 % Iterations
a = zeros(n+1, 2)
a(randperm(numel(a), n)) = 1
%W{i}=a(:,:);
A=a(:,:)
if (sum(A(1,:))>=1) && (sum(A(n+1,:))==0)
A_new=A(:,:)
for j=1:i
* *if W{j}~=W{i} %** Each matrix in the Cell should be different
W{j}=A_new
end
end
% elseif sum(A_new(4,:))<=0
%W{i}=A_new;
i=i+1;
end
end
0 Comments
Accepted Answer
Stephen23
on 8 Aug 2018
Edited: Stephen23
on 8 Aug 2018
One way: use a 3D array, shuffle each matrix so that it is unique:
n = 2;
r = n+1;
z = zeros(r,n,5);
z(1,:,:) = 1;
p = 1;
while p<=size(z,3)
m = z(:,:,p);
m = reshape(m(randperm(numel(m))),r,n);
z(:,:,p) = m;
p = p+~any(all(all(bsxfun(@eq,m,z(:,:,1:p-1)),1),2),3);
end
Each matrix of z is unique:
>> z
z(:,:,1) =
1 0
0 0
0 1
z(:,:,2) =
0 0
0 1
0 1
z(:,:,3) =
1 0
0 1
0 0
z(:,:,4) =
0 0
0 1
1 0
z(:,:,5) =
1 0
0 0
1 0
Just for fun a very memory-inefficient solution:
>> n = 2;
>> m = zeros(n+1,n);
>> m(1,:) = 1;
>> p = perms(m(:)); % ouch! all permutations!
>> q = p(randi(size(p,1),1,5),:); % random subset
>> z = reshape(q.',n+1,n,[])
z(:,:,1) =
0 0
0 0
1 1
z(:,:,2) =
0 0
0 1
0 1
z(:,:,3) =
1 0
0 0
0 1
z(:,:,4) =
0 0
1 1
0 0
z(:,:,5) =
1 1
0 0
0 0
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!