How to put for loop outputs into array?

조회 수: 12 (최근 30일)
Thomas Yates
Thomas Yates 2020년 3월 7일
댓글: Riley Heymann 2022년 3월 25일
I have a for loop that gives output values as the loop iterates and i am trying to put all of the outputs Q(2) into a [1 200] array. Here's what i've got so far, any help would be appreciated.
Q = zeros(1,200);
for i = 5:15/199:20
A = [-2 1 2 0 0 0; 0 0 -2 1 2 0; 0 0 0 0 -2 3; 1 1 0 0 0 0; 0 -1 1 1 0 0; 0 0 0 -1 1 1];
b = [0; 0; 0; i; 0; 0];
Q = A\b;
Q2 = Q(1);
Q2
end

답변 (1개)

Stephen23
Stephen23 2020년 3월 7일
편집: Stephen23 2020년 3월 7일
With MATLAB it is always much simpler and more versatile to loop over indices, rather than looping over data. When you do that, then your task also becomes trivial by using indexing into the output variable. Note that:
  • matrix A does not change in the loop, so should be moved byfore the loop.
  • it adjusts the number of iterations automatically to the number of elements in V.
A = [-2 1,2,0,0,0;0,0,-2,1,2,0;0,0,0,0,-2,3;1,1,0,0,0,0;0,-1,1,1,0,0;0,0,0,-1,1,1];
V = 5:15/199:20;
N = numel(V);
Q = zeros(1,N); % preallocate output array!
for k = 1:N
b = [0;0;0;V(k);0;0];
x = A\b;
Q(k) = x(1);
end
And checking:
>> Q(:)
ans =
2.5294
2.5675
2.6057
2.6438
2.6819
2.7201
2.7582
2.7963
2.8345
2.8726
... more rows here
9.7745
9.8126
9.8507
9.8889
9.9270
9.9651
10.0033
10.0414
10.0795
10.1176
  댓글 수: 1
Riley Heymann
Riley Heymann 2022년 3월 25일
what is the purpose of V? and what is the purpose of b?
I'm trying to copy the process but for a much smaller matrix. Could you rewrite this code for a 8x8 matrix please?

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

카테고리

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

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by