how to create a specific matrix from an array
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Azzi Abdelmalek
2013-9-14
编辑:Azzi Abdelmalek
2013-9-14
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 个评论
更多回答(3 个)
Azzi Abdelmalek
2013-9-14
编辑:Azzi Abdelmalek
2013-9-14
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 个评论
Image Analyst
2013-9-14
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 个评论
Roger Stafford
2013-9-14
编辑:Roger Stafford
2013-9-14
k = 3;
B = hankel(A(1:k),A(k:end));
(Corrected)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!