![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/683993/image.png)
WHAT IS THE SOLUTION FOR
조회 수: 3 (최근 30일)
이전 댓글 표시
Can you help me with the plotlump part these are the existing codes that i have
댓글 수: 1
Stephen23
2021년 7월 14일
편집: Stephen23
2021년 7월 14일
Original question retrieved from Bing Cache:
WHAT IS THE SOLUTION FOR PREALLOCATION?
Can you help me with the plotlump part these are the existing codes that i have
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/683993/image.png)
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
2021년 7월 13일
편집: John D'Errico
2021년 7월 13일
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);
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!