Question

I want to plot A^x * v, where A is a square matrix represent an adjacency matrix in a graph, x is the number of steps, and v is the initial vector.

My goal is to plot the first element of each resulting vector; that is, I want A*v[1], A^2*v[1], A^2*v[1]

I tried

x = 1:1:50 
y = A^x*v
plot(y(1),x)

But got

Error using  ^ 
Inputs must be a scalar and a square matrix.
To compute elementwise POWER, use POWER (.^) instead.

I understand the error, but don't understand how else to approach this problem, just going off Matlab's plot examples.

Thanks in advance for the help!

Was it helpful?

Solution

If you want an almost one liner:

x = 1:1:50;
f = @(z) z(1);
plot(x, arrayfun(@(n) f(A^n*v), x))

The error in what you tried comes from A^x: x cannot be a vector, it must be a scalar because A is a square matrix. See the help of mpower for more info.

OTHER TIPS

How about saving some of the computations?
To get the first element you don't need to compute the entire product A*v.

x = 1:1:50;
f = (n) A(1,:) * ( A^(n-1) ) * v; % returns a scalar - no redundant computation
plot( x, arrayfun( f, x ) ); 

A modification to @Simon's answer, using subsref rather than anonymous function.

x = 1:1:50;
s.type = '()';
s.subs = {1};
plot( x, arrayfun( @(n) subsref( (A^n)*v, s ), x ) );

See also this answer about subsref.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top