Try this

for j=days_left_in_contract-1:-1:2,

counter=days_left_in_contract-j;

difference=min(counter,days_left_with_opportunities);

i=1:1:counter;

interest_rate_vector=exp(-interest_rate*i);

for w=1:difference,

Y(:,1)=sum(cashflow(Eon_pris_t(:,j)>Gaspris_t(:,j),j+1:j+counter,w)*interest_rate_vector);

end

end

end

The most important change is that I've moved the lines

i=1:1:counter;

interest_rate_vector=exp(-interest_rate*i);

outside the for loop. The values of this vectors are not initialize in each for loop actually, so they can be moved safely.

I have done other changes to make the code shorter and to save some for loops. matlab prefers things in matrix form.

By the way, the error that you mentioned before should occur in your original code as well. The error occurs in the line

Y(k,1)=sum(cashflow(i,j+1:j+counter,w).*interest_rate_vector);

and it occurs because sum(...) gives you a number while interest_rate_vector is a vector, and therefore cannot be multiplied using .*. In the code I wrote, this is replaced by *. Anyway, there is still the problem that you are trying to save a vector in Y(k,1), which is only one element, and that cannot be done. So you should check that the your code is right or clarify what Y really is (perhaps a cell array or so).

## 1 Comment

## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/80184-how-to-make-loops-run-faster#comment_156817

⋮## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/80184-how-to-make-loops-run-faster#comment_156817

Sign in to comment.