How to multiply matrices using a for loop

조회 수: 1 (최근 30일)
Rachel Buckland
Rachel Buckland 2018년 1월 17일
댓글: Kaushik Lakshminarasimhan 2018년 1월 18일
I have the equation p(t+1)=p(t)*P. p(t) is the matrix [p1(t) p2(t) p3(t) p4(t)] with p(0)=[1 0 0 0] and P is a 4x4 matrix.
I need to create a for loop that runs through the matrix multiplications until it reaches a certain p1(t). Can anyone help? Thanks.

답변 (1개)

Kaushik Lakshminarasimhan
Kaushik Lakshminarasimhan 2018년 1월 17일
p = rand(4,1); % 4x1 vector
P = rand(4,4); % 4x4 matrix
pstar = 10;
while p(1)<pstar % stop multiplying if p(1) reaches a certain pstar
p = P*p;
end
  댓글 수: 2
Rachel Buckland
Rachel Buckland 2018년 1월 17일
I'm trying to accomplish this using a for loop do you know how to do it that way?
Kaushik Lakshminarasimhan
Kaushik Lakshminarasimhan 2018년 1월 18일
for loop is not ideal here because you do not know how many iterations you'll need a priori (unless you worked out the math). Is there a reason you insist on a for loop? If you absolutely must use it, here's one way:
p = rand(4,1); % 4x1 vector
P = rand(4,4); % 4x4 matrix
pstar = 10;
for i=1:1e4 % allow for a large enough number of iterations
p = P*p;
if p(1)>pstar, break; end
end

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by