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

2 次查看(过去 30 天)
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