FOR loop with matrices

I am working on coding a problem where we have Matrix A (3x3) and vector x0 (3x1).
x(k+1) = A*x0 where k =0 this new x vector will then be multiplied to A
so x(1+1)= A*x1 and so on.
the only thing staying constant is A matrix with the vector x changing. But i want to store and keep each vector x.
I am having troubles writing this.

3 个评论

Please post, what you have tried so far. It needs only 3 lines and it is not clear if this is a homework problem.
Do you want A*x0, (A^2)*x0, (A^3)*x0, etc, and all the results stored in a single result matrix?
James that is not what I want.
Matrix A is a 3x3 that will always containt the same elements.
Vector x0 (3x1) is the "initializer"
I want to multiply A*xk=xk+1
So first would be A*x0=x1
Then A*x1=x2 and so on.
Jan ---> I have
A = [3x3 stuff]
x0 = [3x1 stuff]
for k=0:10
x(k+1)=A*x(k)
i cant figure how to continue the for loop so it takes x1 and keeps running it

请先登录,再进行评论。

 采纳的回答

Jan
Jan 2012-3-10
A = rand(3, 3);
x = rand(3, 1);
v = zeros(11, 3); % Pre-allocation!
v(1, :) = x;
for k = 1:10
v(k + 1, :) = A * v(k, :);
end
Then the vectors x_i are stores as columns of the matix v. Another approach with a cell:
v = cell(1, 11); % pre-allocation!
v{1} = x;
for k = 1:10
v{k + 1} = A * v{k};
end
Btw., look at James' comment again:
x1 = A * x0
x2 = A * x1 = A * A * x0 = A^2 * x0
x3 = A * x2 = ... = A^3 * x0
...

6 个评论

My apologies James. I did not think of doing it this way.
That would work. However, I would want to store the results in different vectors.
The vectors x1, x2, x3 ... are the ones I want to compare.
I guess my question with James approach is how would you store the vectors using a for loop with his equation because it would be
xn = A^n * x0 right?
this is what i have so far but i keep getting an error
A = [.70,.15,.10;.15,.80,.30;.15,.05,.60]
x0 = [300;350;200]
for n = 1:10
x(n) = A^(n) * x0
end
error: In an assignment A(I) = B, the number of elements in B and
I must be the same.
for n = 10:-1:1
x(:,n) = A^(n) * x0
end
and what if i didnt want to store it in a matrix but instead individual vectors x1, x2, x3 ...
this is bad way
please read http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F
x{1}, x{2}, ... is a good way to store the individual vectors. It is a bad idea, to hide the index in the name of the variable, because complicated methods to create complicated names of variables require further complicated methdos to access these variables later.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by