2

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!

bla
  • 25,846
  • 10
  • 70
  • 101

3 Answers3

4

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.

Simon
  • 31,675
  • 9
  • 80
  • 92
2

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 ) ); 
Shai
  • 111,146
  • 38
  • 238
  • 371
1

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.

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371