how to create a specific matrix from an array

1 回表示 (過去 30 日間)
Pierre
Pierre 2013 年 9 月 14 日
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];

採用された回答

Azzi Abdelmalek
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)

その他の回答 (3 件)

Azzi Abdelmalek
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))

Image Analyst
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.

Roger Stafford
Roger Stafford 2013 年 9 月 14 日
編集済み: Roger Stafford 2013 年 9 月 14 日
k = 3;
B = hankel(A(1:k),A(k:end));
(Corrected)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by