How to create overlapping blocks using a matrix rows ?

Hello,
Suppose that we have the matrix A where:
A=[0 1 0 0 1 1 0 1 0 1 0 1 0]
now, we want to create 10 blocks where each block contains four bits and put it in the cell matrix B where:
B= {[0,1,0,0] [1,0,0,1] [0,0,1,1] [0,1,1,0] [1,1,0,1] [1,0,1,0] [0,1,0,1] ...
[1,0,1,0] [0,1,0,1] [1,0,1,0] }
As you can see, each block is resulted by shifting a sliding window (of size four) by one bit each time, for example:
% the sequence 01001 will gives:
% [0,1,0,0] and [1,0,0,1]
So how I can implement that?

2 Kommentare

Are you sure that B looks like you want it to look?
yes. it supposed to be cell matrix. I editted the question.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Star Strider
Star Strider am 19 Jan. 2019
Try this:
A=[0 1 0 0 1 1 0 1 0 1 0 1 0];
S = hankel(A, [0 1 1 1]);
S = S(1:10,:);
B = mat2cell(S, ones(1,size(S,1)), size(S,2))';
If you prefer a loop:
L = 4;
for k1 = 1:numel(A)-L
S(k1,:) = A(k1:k1+L-1);
end
B = mat2cell(S, ones(1,size(S,1)), size(S,2))';
B{:} % Display Result (Delete Later)

7 Kommentare

Great ! Thanks alot.
As always, my pleasure!
@Star Strider
excuse me, what changes should I do on the loop of matrix A have several rows ?
regards,
The hankel code will likely not work in that event.
I would do something like this:
A = randi([0 1], 5, 13); % Create ‘A’
L = 4;
for k1 = 1:size(A,1)
for k2 = 1:size(A,2)-L+1
S(k1,k2,:) = A(k1:k1+L-1);
end
end
B = mat2cell(S, ones(1,size(S,1)), ones(1,size(S,2)), size(S,3));
B = cellfun(@squeeze, permute(B, [2,1,3]), 'Unif',0);
My code would require an extra loop for the rows.
Great!
I was not sure what result you wanted with a matrix (rather than a vector) for ‘A’.
Sarah A
Sarah A am 20 Jan. 2019
Bearbeitet: Sarah A am 20 Jan. 2019
This is the final form, I wasnt do it without your help so Thank you :)
matrix = [ 0 0 0 0 1 1 0 1 0 1 1 1 1; 0 1 0 1 1 1 0 0 1 1 1 0 1]
for i=1:size(matrix,1)
A=matrix(i,:);
S = hankel(A, [0 1 1 1]);
L = 4; %sliding window size
S = S(1:(size(A,2)-(L-1)),:);
for k1 = 1:numel(A)-L
S(k1,:) = A(k1:k1+L-1);
end
B = mat2cell(S, ones(1,size(S,1)), size(S,2))';
C{i}=B;
end
and the output will be:
C(1,1):
[0,0,0,0][0,0,0,1][0,0,1,1][0,1,1,0][1,1,0,1][1,0,1,0][0,1,0,1][1,0,1,1][0,1,1,1][1,1,1,1]
C(1,2):
[0,1,0,1][1,0,1,1][0,1,1,1][1,1,1,0][1,1,0,0][1,0,0,1][0,0,1,1][0,1,1,1][1,1,1,0][1,1,0,1]
As always, my pleasure!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by