saving for loop results not working

12 views (last 30 days)
Hi everyone, I'm struggling to save my results from a FOR loop. I have watched some videos and look at other peoples questions to try and find what I'm missing (which is probably something simple) but I can't get it to work. I have tried the following codes
I = 800/365*1.5;
O = 400*17000/1000000;
d = 1:3;
sc = 8;
sum = zeros(length(d),1);
for d = 1:length(d)
sc = sc+I-O;
sum = sc
end
Thi code keeps doesn't save all 3 results.
I = 800/365*1.5;
O = 400*17000/1000000;
sc = 8;
for d = 1:3
sc(d) = sc+I-O;
end
This code keeps saying there are different elements between right side and left side.
Can anyone please explain to me what im doing wrong and how to fix it. All I want is to do a loop for 3 counts (3 days) where full capacity is 8 of a tank, and eveyday there is an infow and an outflow. I would like to show the results in 3x1 table along with the inflow of every day and the outflow of everyday (both which will be constant).
thanks

Accepted Answer

Stephen23
Stephen23 on 18 Aug 2019
Edited: Stephen23 on 18 Aug 2019
"Can anyone please explain to me what im doing wrong and how to fix it."
Your first code does not store/allocate/sum the output in any way, so you simply discard the output of each loop iteration, keeping only the results of the last iteration.
"This code keeps saying there are different elements between right side and left side."
Your second code works without error on the first and second iterations, but then on the third iteration you forgot to consider that sc will now have size 1x2, to which you add some scalars, thus also giving an output of size 1x2. However you then try to allocate these two elements into one element on the LHS:
sc(d) = sc+I-O;
% ^ indexing refers to one element of sc
% ^^ but on third iteration this already has size 1x2
One element of a numeric array contains one value: it is an error to try an store multiple elements/values into one element of a numeric array.
You do not describe your algorithm at all, but a few small changes allows your code to run and store its output values (you need to check the algorithm yourself):
I = 800/365*1.5;
O = 400*17000/1000000;
% Preallocate sc:
N = 3;
sc = nan(1,N);
sc(1) = 8; % day 1
for d = 2:N % days 2:N
sc(d) = sc(d-1)+I-O;
end
Giving:
>> sc
sc =
8 4.4877 0.97534

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!