# WHAT IS THE SOLUTION FOR

1 view (last 30 days)
My mee on 13 Jul 2021
Edited: Stephen on 14 Jul 2021
Can you help me with the plotlump part these are the existing codes that i have
Stephen on 14 Jul 2021
WHAT IS THE SOLUTION FOR PREALLOCATION?
Can you help me with the plotlump part these are the existing codes that i have
FOR LUMPSUM
% this while loop will run untill user enters valid values of
% principal , number of years , interest rate
while(1)
[val,Principal,Number,Interest] = inputvalues;
if(val(1) == 0)
disp('Entered Principal Amount is wrong ');
disp('Please enter the details again ');
end
if(val(2) == 0)
disp('Entered Number of years is wrong ');
disp('Please enter the details again ');
end
if(val(3) == 0)
disp('Entered Rate of Interest is wrong ');
disp('Please enter the details again ');
end
if(sum(val) == 3)
break;
end
end
% function call to plotlump function
plotlump(Principal,Number,Interest);
FOR INPUVALUES.M
function [v,P,n,i] = inputvalues
% Taking input from the user
P = input('Enter the Prinicipal Amount Invested : ');
n = input('Enter number of years : ');
i = input('Enter the rate of interest : ');
% errorcheck function call
v = errorcheck(P,n,i);
end
FOR ERRORCHECK.M
function value = errorcheck(prin,num,inter)
% value is variable which holds the state of
% principal , number of years , interest
% If they are valid , then value holds as 1 ( denoting they are valid )
% else value holds 0 ( indicating they are wrong )
value = [1,1,1];
if(prin <= 0)
value(1) = 0;
end
FOR PLOTLUMP.M
function plotlump(pric,numb,inter)
% This loop will calculate value of S
for i = 1:numb
S(i) = pric * (1 + (inter/100))^i;
end
FOR PLOTLUMP IT SAYS THAT Line 8: The variable 'S' appears to change size on every loop iteration.
Consider preallocating for speed.
HOW CAN I FIX THIS?

John D'Errico on 13 Jul 2021
Edited: John D'Errico on 13 Jul 2021
Why? Is there a problem? Are you worried that your code is taking 1 millisecond longer to execute in this case?
My point is, this is a suggestion that this code is not as efficient as it might be. It is NOT an error message. Just a suggestion to improve your code. There are some codes where the time would be significant. But for moderately small values of numb, you have now spent far more time worrying about the message than you will use in CPU time.
The solution is to use zeros to create the vector S, BEFORE THE LOOP. Use zeros. You know what the final size of S will be. Something like:
S = zeros(1,numb);