Vectorization

9 次查看(过去 30 天)
Yusa Topcu
Yusa Topcu 2012-4-16
A= 1000; %amount borrowed
n= 12 ; % number of payments per year
for r= 0.1 : 0.01 : 0.2
fprintf ('%4.0f%' , 100*r ) ;
for k = 15 : 5 25
temp = (1 + r/n) ^(n*k) ;
P = r*A * temp / (n*(temp-1));
fprintf ( '%10.2f' , P) ;
end
end
How can I vectorized these two nested FORs ?
[Edited, Jan Simon, Code formatted]

采纳的回答

Andrei Bobrov
Andrei Bobrov 2012-4-16
A = 1000;
n = 12;
r = .1:.01:.2;
k = (15 : 5 :25).';
t1 = bsxfun(@(r,k)(1 + r/n) .^(n*k),r,k);
P1 = A*bsxfun(@times,r,t1 ./ (n*(t1-1)));
P = reshape([100*r;P1],1,[])
variant with one cycle
A = 1000;
n = 12;
r = .1:.01:.2;
k = 15 : 5 :25;
nr = numel(r);
nk = numel(k)+1;
out = zeros(1,nr + (nk-1)*nr);
for ii = 1:nr
t = (1 + r(ii)/n) .^(n*k);
out(nk*ii+(-3:0)) = [100*r(ii), A*r(ii)*t./(n*(t-1))];
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Chemistry 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by