2
votes

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!

3
What are the dimensions of A?Justin Peel
A changes, but a specific case is 10 by 10.phoenixairs
You need to do a for loop over the x's rather than trying to do all of the exponents at once. I don't know a way to vectorize that operation.Justin Peel
When A is not a square matrix, A^n is not defined. Thats why the error comes.Autonomous
@Parag, A is square, the problem is that x is not a scalar.Justin Peel

3 Answers

4
votes

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.

2
votes

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 ) ); 
1
votes

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.