how to create a specific matrix from an array

2 visualizzazioni (ultimi 30 giorni)
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];

Risposta accettata

Azzi Abdelmalek
Azzi Abdelmalek il 14 Set 2013
Modificato: Azzi Abdelmalek il 14 Set 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)

Più risposte (3)

Azzi Abdelmalek
Azzi Abdelmalek il 14 Set 2013
Modificato: Azzi Abdelmalek il 14 Set 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))

Image Analyst
Image Analyst il 14 Set 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.

Roger Stafford
Roger Stafford il 14 Set 2013
Modificato: Roger Stafford il 14 Set 2013
k = 3;
B = hankel(A(1:k),A(k:end));
(Corrected)

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by