Matrix operation with for loop
显示 更早的评论
Hi everyone,
I am trying to model a physics problem and I need to calculate the states of my object at each step. To do so I have to do a matrix multiplication as follow
x(i+1) = Ad*x(i)+Bu*u(i)+w
While,
x is 4x1,
Ad is 4x4 and constant,
x0 is my initial state,
Bu is 4x1 and constant,
u is 1x1,
and w is 4x1 and constant.
I wrote a for loop for matrix multiplication, but I have a problem with setting up my initial state vector in the loop. I really appreciate it if you could help me out. Thank you.
11 个评论
James Tursa
2018-2-23
Are you sure that shouldn't be Ad*x instead of Ad*x(i)?
KSSV
2018-2-23
It should be an easy job......copy your code here......
per isakson
2018-2-25
编辑:per isakson
2018-2-25
Study and run
x = nan( 1, 12 );
x0 = 17; % initial state
%
x(1) = x0;
for jj = 2 : length(x)
x(jj) = x(jj-1) + randi([-3,3]);
end
and inspect the result
>> x
x =
17 20 17 20 21 18 16 16 19 22 20 23
>>
Sasha M
2018-2-25
Image Analyst
2018-2-25
does x(i) represent the i'th index of x, or perhaps does it mean the whole x array at iteration or run #i? In other words, if you're running 10 iterations and you're calculating x at iteration #4
"x at iteration 4" = Ad*"x at iteration 3" + Bu*"u at iteration 3"+w
Otherwise x(4) depends on x(3), and x(3) depends on x(2), and x(2) depends only on x(1), so it doesn't matter if x starts out as a scalar or a vector. And what is x0? Do you mean the first set of 4 x values? Or do you mean the x value at the first x index, in other words x0 is really x(1)? Please explain more clearly.
per isakson
2018-2-25
"I understand the code you wrote" If so, how come
- I cannot see x0 in your code
- all your loops start from 1 and not 2
- the rhs includes x(i2) rather than x(i2)-1
With a vector
x = nan( 4, 12 );
x0 = repmat( 17,[4,1]); % initial state
%
x(:,1) = x0;
for jj = 2 : size(x,2)
x(:,jj) = x(:,jj-1) + randi([-3,3],[4,1]);
end
inspect x
>> x
x =
17 20 18 20 18 17 20 19 19 19 17 15
17 20 18 16 14 16 15 15 17 17 19 20
17 17 19 22 23 24 26 23 26 23 22 20
17 14 12 11 11 11 13 10 7 6 6 7
>>
Sasha M
2018-2-25
per isakson
2018-2-25
I assume that your code in the previous comment is supposed to be Matlab code.
- "x(i) refers to the entire state of x (4x1) at i'th iteration." In Matlab code, if i is a scalar then x(i) is a scalar
- "x0 is really my x(1)" However, x(1) is overwritten in the first iteration of the loop.
- In your x(i1) = Ad(i1,i2)*x(i2)+Bu(i1)*u(i)+w(i1);, for every i1 the scalar, x(i1), is written once and then overwritten three times.
- I'm lost
回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!