Hi,
Assume I have a vector v and a square matrix A
v = [1, 2, 3, 4, 5];
A = randn(5);
I want to create a matrix
m = [v*A; v*A^2; v*A^3; ..; v*A^n]
Where n is a user input and ^ results in the matrix product operator (not dot product .^)
I can do that easily with a loop. Is there a quicker way of doing this without using a loop?

 채택된 답변

Matt J
Matt J 2019년 5월 17일
편집: Matt J 2019년 5월 17일

0 개 추천

No, a for-loop is fastest, but you want to implement it the right way, with a recursive update,
m=repmat(v*A,n,1); %pre-allocate
for i=2:n
m(i,:) = m(i-1,:)*A;
end
That way, the process takes only n matrix multiplications.

추가 답변 (1개)

Adam Danz
Adam Danz 2019년 5월 17일
편집: Adam Danz 2019년 5월 20일

0 개 추천

No loop method:
m = cell2mat(arrayfun(@(x)v*A.^x,1:n,'UniformOutput',false)')
Test result with loop version
mm = zeros(6,5);
for i = 1:n
mm(i,:) = v*A.^i;
end
isequal(m,mm) % = 1, same result
Which is faster?
To test speed, I ran 100,000 iterations of the one-liner and the same number of iterations of the for-loop (just the loop, the pre-allocation was done before the timer started). The variable n=20. The median speed of the for-loop was 2.7 times faster than the arrayfun() method (p<0.001 wilcox signed rank test). The for-loop is the clear winner for speed.

댓글 수: 2

Rik
Rik 2019년 5월 17일
Given that A is a square matrix, Jean Dupin might actually mean ^ instead of .^ as the operation to be applied to A.
Adam Danz
Adam Danz 2019년 5월 17일
That's a good point Rik. Jean Dupin, be sure to apply the correct operation.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2019년 5월 17일

편집:

2019년 5월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by