combining elements in array

1 回表示 (過去 30 日間)
pallavi patil
pallavi patil 2022 年 2 月 18 日
編集済み: Voss 2022 年 2 月 18 日
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 Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by