for loop issue not all answer printing out
3 ビュー (過去 30 日間)
古いコメントを表示
Anastasia Zistatsis
2021 年 1 月 11 日
コメント済み: Anastasia Zistatsis
2021 年 1 月 11 日
This is my assignment: Write an M-file to compute A. Test it with P =$100 , 000 and an interest rate of 3.3 % ( r = 0.033 ). Use a for loop to compute results for n= 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , and 10. Then display the results in a table with headings and columns for n and A.
I've written all the code and everything works, but my table only shows n=10 and the corresponding answer. I really don't understand for loops enough to know what to fix in mine
function A = InterestPayment(P,r,n)
P = 100000;
r = 0.033;
for n=1:10
A = P*((r*(1+r)^n)/((1+r)^n-1));
end
A = P*((r*(1+r)^n)/((1+r)^n-1));
T= table (n',A', 'VariableNames',{'n','A'})
0 件のコメント
採用された回答
Doddy Kastanya
2021 年 1 月 11 日
Hi Anastasia,
The problem is you did not store the results as a vector; therefore, when you printed out the table, only the last value of A is shown. The updated version below should work. Another thing that you might want to do is to define the calling variables from outside the function so you can use it for other values as well.
P = 100000;
r = 0.033;
n=10;
InterestPayment(P,r,n);
function A = InterestPayment(P,r,n)
for i=1:n
A(i) = P*((r*(1+r)^i)/((1+r)^i-1));
end
T= table ([1:n]',A', 'VariableNames',{'n','A'})
end
その他の回答 (1 件)
David Hill
2021 年 1 月 11 日
function T = InterestPayment(P,r)
for n=1:10
A(n) = P*((r*(1+r)^n)/((1+r)^n-1));
end
T= table ((1:10)',A', 'VariableNames',{'n','A'});
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!