For loop trouble!

1 次查看(过去 30 天)
skagawa23
skagawa23 2016-9-22
What I am trying to do is, assume the first vector to be [1; 1; 1] and run the loop until difference in u is less than 0.0001. Before going into the loop, for some reason, I cannot set the first vector by saying u(1) = [1; 1; 1]
Here is what I have:
w = 100;
gravity = 32.2*12;
m = w/gravity;
k = 326.32;
K = [2 -1 0; -1 2 -1; 0 -1 1];
K = k*K
Kinv = inv(K)
M = [1 0 0; 0 1 0; 0 0 0.5];
M = m*M
u(1) = [1; 1; 1];
i = 1;
for i = 1:10;
Mstar = u(i) * M * u(i)'
Kstar = u(i) * K * u(i)'
L(i) = Kstar(i) / Mstar(i)
RHS = L(i) * M * u(i)'
u(i+1) = Kinv * RHS(i)
Diff = u(i+1) - u(i);
if Diff > 0.0001;
u(i+1) = u(i+1)
else
break
end
end

回答(3 个)

Walter Roberson
Walter Roberson 2016-9-22
u(1) is a specific numeric array locations. Numeric array locations can only hold a single numeric value; you are trying to store three numeric values in that one location.
You probably just want
u = [1; 1; 1];

Christoph F.
Christoph F. 2016-9-22
编辑:Christoph F. 2016-9-22
I assume you want to keep the intermediate values of u?
In that case, use u(:, 1) = [1; 1; 1] (or u = [1; 1; 1]). Then you can access the i-th version of u with u(:, i).
However, you may want to initialize u as a matrix, to avoid time-consuming resizing of u in the loop. This can be done by initializing u with u = zeros(3, 11); u(:, 1) = [1; 1; 1];

Andrei Bobrov
Andrei Bobrov 2016-9-22
编辑:Andrei Bobrov 2016-9-22
w = 100;
gravity = 32.2*12;
m = w/gravity;
k = 326.32;
K = [2 -1 0; -1 2 -1; 0 -1 1];
K = k*K;
M = [1 0 0; 0 1 0; 0 0 0.5];
M = m*M;
u = [1; 1; 1];
for ii = 1:10;
Mstar = u(:,ii)' * M * u(:,ii);
Kstar = u(:,ii)' * K * u(:,ii);
L = Kstar / Mstar;
RHS(:,ii) = L * M * u(:,ii);
u(:,ii+1) = K\RHS(:,ii);
Diff1 = u(:,ii+1) - u(:,ii);
if norm(Diff1) < 0.0001
break
end
end

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by