필터 지우기
필터 지우기

how to create a specific matrix from an array

조회 수: 3 (최근 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 CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by