I have an array : A = [0 3 5 7 8 9 1 3 4 0]. I want to convert it into 1x3 matrices such as [0 3 5], [3 5 7], [5 7 8]...[3 4 0] and so on.
My code is:
clc
A = [0 3 5 7 8 9 1 3 4 0];
B = zeros(1, 3);
r=1;
c=3;
for i = r:c
for k = 1:3
B(k) = A(i)
r=r+1;
c=c+1;
end
end
But it doesn't seem to be working correct. Can somebody help?

 Accepted Answer

Use the hankel (link) function to create a Hankel matrix:
A = [0 3 5 7 8 9 1 3 4 0];
B = hankel(A,A(1:4:end))
B =
0 3 5
3 5 7
5 7 8
7 8 9
8 9 1
9 1 3
1 3 4
3 4 0
4 0 8
0 8 4

2 Comments

I wanted to write this code without using any functions. I have to just use the loops.
I now suspect this is homework, rather than your simply not knowing about Hankel matrices.
Since I’ve already started to solve it, I’ll give you my approach:
A = [0 3 5 7 8 9 1 3 4 0];
B = zeros(size(A,2)-2,3);
for k1 = 1:numel(A)-2
B(k1,1:3) = A(k1:k1+2);
end
B =
0 3 5
3 5 7
5 7 8
7 8 9
8 9 1
9 1 3
1 3 4
3 4 0
There may be other approaches.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!