How to use a for loop to get previous values to calculate next one

조회 수: 2 (최근 30일)
Holly Janes
Holly Janes 2020년 12월 19일
답변: Walter Roberson 2024년 9월 5일
I am having trouble with my foor loop. I want to get the previous value to use in the next calculated value.
x(1) = A+B*(-K*cl^(k-1));
for k=0:4
x(k) = A*x(k-1) + B*(-K*cl^(k-1));
end
Error I keep getting is:
Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.

답변 (2개)

Deepak
Deepak 2024년 9월 5일
I understand that you have written a MATLAB code to generate an array “x” that calculates and stores the values at next index from the previous one, but you are getting the error:
Unable to perform assignment because the indices on the left side are not compatible with the size of the right side”.
The error occurs because, in MATLAB, array indices start at 1 instead of 0. Therefore, the loop should begin at (k = 2), since the value at index 1 is already assigned before the loop starts. Additionally, to optimize the code, you can initialize the array "x" with zeros before the loop by using the "zeros" function.
Here is the updated MATLAB code for the same:
% Preallocate x with the correct size
x = zeros(1, 5);
% Initial value
x(1) = A + B * (-K * cl^(1-1));
% Loop to calculate subsequent values
for k = 2:5
x(k) = A * x(k-1) + B * (-K * cl^(k-1));
end
disp(x);
Please find attached the documentation of array indexing and zeros function for reference:
I hope this was helpful.
  댓글 수: 1
Walter Roberson
Walter Roberson 2024년 9월 5일
If we assume that
x(1) = A+B*(-K*cl^(k-1));
worked, then A must have been scalar, and either the other elements are scalar or else they happen to be just the right size for matrix multiplication to reduce down to scalars.
But then when we examine
for k=0:4
x(k) = A*x(k-1) + B*(-K*cl^(k-1));
the A will be retrieved first; it must be scalar for the previous statement to have worked. Then x(k-1) would be evaluated, and because k = 0 first, that would be x(-1) . x(-1) would fail with "Array indices must be positive integers or logical values." rather than an error about a mismatch in the number of elements.
So although you are correct to point out indexing at 0 is a problem with the code, it is not the most immediate error.

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


Walter Roberson
Walter Roberson 2024년 9월 5일
@Deepak correctly points out problems with indexing at 0 or -1. But that error would have priority . Because that error does not occur, we can tell that the real problem is in the statement
x(1) = A+B*(-K*cl^(k-1));
Possibly A is non-scalar. Or possibly B*(-K*cl^(k-1)) is non-scalar.

카테고리

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