How do I update a matrix in for loop (indexing problem)
    조회 수: 7 (최근 30일)
  
       이전 댓글 표시
    
Hello,
I have a matrix A and a vector u. I want to run a for loop to update the vector u. The operation is easy, I will multiple A by u (result is another vector denoted by z). Pick the largest element in z (result is scalar denoted by m). Update u by dividing the vector z with m. I don't know how to index the matrix so I used cell notation but that might not be correct.
     A=[1 2 3 4; 5 6 7 8 ; 9 10 11 12; 13 14 15 16];
     u= ones (4,1);
     for s=1:10
         z{s}= A*u{s};
         m(s)= max(z{s});
         u{s} = z{s}/m(s);
    end
Any suggestions would be very helpful.
댓글 수: 0
답변 (1개)
  Guillaume
      
      
 2015년 8월 20일
        
      편집: Guillaume
      
      
 2015년 8월 20일
  
      If you don't want to keep around the result of each step, then your algorithm is simply:
A = [1 2 3 4; 5 6 7 8 ; 9 10 11 12; 13 14 15 16];
u = ones (4,1);
for s = 1:10
   z = A * u;
   m = max(z);
   u = z / m;
end
If you do want to keep the intermediary results, then you can indeed use cell arrays, like this:
    A = [1 2 3 4; 5 6 7 8 ; 9 10 11 12; 13 14 15 16];
    uinitial = ones (4,1);
    numsteps = 10;
    u = cell(1, numsteps+1); z = cell(1, numsteps); m = cell(1, numsteps);
    u{1} = uinitial;
    for s = 1:numsteps
       z{s} = A * u{s};
       m{s} = max(z{s});
       u{s+1} = z{s} / m{s};
    end
Or you could use arrays which will be easier to inspect
    A = [1 2 3 4; 5 6 7 8 ; 9 10 11 12; 13 14 15 16];
    uinitial = ones (4,1);
    numsteps = 10;
    u = zeros(4, numsteps+1); z = zeros(1, numsteps); m = zeros(1, numsteps);
    u(:, 1) = uinitial;
    for s = 1:numsteps
       z(s) = A * u(:, s);
       m(s) = max(z(s));
       u(:, s+1) = z(s) / m(s);
    end
댓글 수: 0
참고 항목
카테고리
				Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
