combining elements in array

1 次查看(过去 30 天)
A= [1 1 1 0 1 1 0 0 ]
A2 = [1 0 1 0]
A3 = [ 1 0 ? ]
A4 = [0 0]
In this , array has either ones or zeros. Array A2 is created by applying and logic on A(1) & A(2)., next elementt in A2 is A(3) & A(4) so on ....
Array A3 is created by anding A(1)& A(2) & A(3), next element is A(4)& A(5) & A(6)
Array A4 is created by anding A(1)& A(2) & A(3) & A(4).
I want to create such arrays which will go to length of the vector A. Like Array A8 = A(1)& A(2) & A(3) & A(4)& A(5) & A(6)& A(7)& A(8).
my code is
%%%%%%%%
for A2
sz = length(A);
if rem(sz,2)==1
d1 = reshape(A(1:end-1,:),2,[]);
A2 = [d1(1,:)&d1(2,:)]';
end
%%%%%%%%%
%for A3
if (mod(sz,3)==2)
d1 = reshape(A(1:end-2,:),3,[]);
A3 = [d1(1,:)&d1(2,:)&d1(3,:)]';
elseif (mod(sz,3)==1)
d1 = reshape(A(1:end-1,:),3,[]);
A3= [d1(1,:)&d1(2,:)&d1(3,:)]';
else(mod(sz,3)==0)
d1 = reshape(A,3,[]);
A3= [d1(1,:)&d1(2,:)&d1(3,:)]'
end
%%%%%%%%%%%%
%for A4
if rem(sz,4)==3
d1 = reshape(A(1:end-3,:),4,[]);
A4 = [d1(1,:)&d1(2,:)&d2(3,:)&d1(4,:)]';
elseif rem(sz,4)==2
d1 = reshape(A(1:end-2,:),4,[]);
Yval_pred4 = [d1(1,:)&d1(2,:)&d1(3,:)&d1(4,:)]';
elseif rem(sz,4)==1
d1 = reshape(A(1:end-1,:),4,[]);
A4 = [d1(1,:)&d1(2,:)&d1(3,:)&d1(4,:)]';
else
d1 = reshape(A,4,[]);
A4= [d1(1,:)&d1(2,:)&d1(3,:)&d1(4,:)]';
end
Is there a simpler way to do this. I have very long A aray and i cant apply divisibilty test for evrery number to get A5, A6, A7 array and so on

采纳的回答

Voss
Voss 2022-2-18
编辑:Voss 2022-2-18
A= [1 1 1 0 1 1 0 0 ];
M = 2; % number of elements of A to group together in sets
N = numel(A);
d = reshape(A(1:N-rem(N,M)),M,[]);
new_A = all(d,1)
new_A = 1×4 logical array
1 0 1 0
Using that same construction in a loop over different M values can allow you to do several easily:
A= [1 1 1 0 1 1 0 0 ];
N = numel(A);
M = 1:N; % for example
new_A = cell(1,numel(M));
for m = 1:numel(M)
new_A{m} = all(reshape(A(1:N-rem(N,M(m))),M(m),[]),1);
end
disp(new_A);
{[1 1 1 0 1 1 0 0]} {[1 0 1 0]} {[1 0]} {[0 0]} {[0]} {[0]} {[0]} {[0]}

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by