how to create a specific matrix from an array
2 views (last 30 days)
Show older comments
Hi,
Is there anyone who can help me to create a specific matrix B from an array A as following? I need a better method which spend less time to create this matrix. Thanks.
A=[1 2 3 4 5 6 7] B=[1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7];
0 Comments
Accepted Answer
Azzi Abdelmalek
on 14 Sep 2013
Edited: Azzi Abdelmalek
on 14 Sep 2013
A=[1 2 3 4 5 6 7]
m=5;
n=numel(A);
id=bsxfun(@plus,repmat(1:n,3,1),(0:2)');
id=id(:,1:m);
B=A(id)
0 Comments
More Answers (3)
Azzi Abdelmalek
on 14 Sep 2013
Edited: Azzi Abdelmalek
on 14 Sep 2013
A=[1 2 3 4 5 6 7]
m=5;
n=numel(A);
B=zeros(3,m);
for k=1:3
B(k,:)=A(k:k+m-1);
end
disp(B)
%or
m=5;
n=numel(A)
B=cell2mat(arrayfun(@(x) A(x:x+m-1),(1:3)','un',0))
0 Comments
Image Analyst
on 14 Sep 2013
I think creating that B would be exceptionally fast, though you didn't use A at all when you created it. I assume you want something more general and flexible but you didn't state what parameters can be adjustable. For example, is the number of columns in A variable? What about the values of A, can they be any random numbers, or are they integers and always exactly 1 more in each column to the right? Can A be rand(1,42) - an array of 42 random numbers?
Now, what about B? How tall can it be? Does it go just until you reach the last number in A, or can it be taller and you keep shifting the rows to the left and adding 1? Is the number of columns in B always 5? Or always 2 less than the number of columns in A? Or can it be any number of columns that you specify? Can B have 3 or 4 or 11 columns?
Please be clear in how you want to generalize this. Otherwise the way you created B seems to be fast and it works.
0 Comments
Roger Stafford
on 14 Sep 2013
Edited: Roger Stafford
on 14 Sep 2013
k = 3;
B = hankel(A(1:k),A(k:end));
(Corrected)
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!