Create a vector of vector exponents
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Jean Dupin
am 17 Mai 2019
Bearbeitet: Adam Danz
am 20 Mai 2019
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?
0 Kommentare
Akzeptierte Antwort
Weitere Antworten (1)
Adam Danz
am 17 Mai 2019
Bearbeitet: Adam Danz
am 20 Mai 2019
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 Kommentare
Rik
am 17 Mai 2019
Given that A is a square matrix, Jean Dupin might actually mean ^ instead of .^ as the operation to be applied to A.
Adam Danz
am 17 Mai 2019
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!