Each matrix of the of the cell should be unique/different from each other

1 回表示 (過去 30 日間)
P K
P K 2018 年 8 月 8 日
再開済み: Walter Roberson 2018 年 12 月 22 日
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

採用された回答

Stephen23
Stephen23 2018 年 8 月 8 日
編集済み: Stephen23 2018 年 8 月 8 日
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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by