Reputation: 62588
MATLAB's syntax differs somewhat from the traditional DO loops "logic" which iterates over indexes one at a time. With that in mind, what would be a more proper way to write the following, so it runs a bit faster but is still relatively clear for someone not too familiar with MATLAB.
KT = 0.;
for i=1:37
dKT = KTc(i,1) *const2^KTc(i,2) *const3^KTc(i,3) *const4^KTc(i,4) *const5^KTc(i,5);
KT = KT + dKT;
end
sprintf('KT = %f10.8', KT);
KTc is a matrix 37x5 (if it helps, only the (i,1) values are REAL values, the rest are INTEGERs)
All constants are REAL scalars.
Upvotes: 1
Views: 143
Reputation: 12554
Your lines (in the original question) correctly:
KT = 0.;
for i=1:37
dKT = KTc(i,1) *const2^KTc(i,2) *const3^KTc(i,3) *const4^KTc(i,4) *const5^KTc(i,5);
KT = KT + dKT;
end
sprintf('KT = %f10.8', KT);
On the other hand I would suggest
KT = repmat([1; const2; const3; const4; const5], 1, n) .^ KTc;
KT(1,:) = KTc(1,:);
KT = sum(KT(:));
Loops are rarely used in a real matlab-style program. The reason for that is, that although my second solution does more operations, in practice it is quicker due to more optimal caching at the processor, parallelization, and other possible optimizations which are done silently in the background.
UPDATE: (explanation on repmat)
I think repmat is short for "replicate matrix". What it does really is best explained with two typical examples:
v_row=[1 2 3];
repmat(v_row, 2, 1);
%result:
[1 2 3
1 2 3]
v_col=[1;2;3]; % I could also write v_col=v_row';
repmat(v_col, 1, 2);
[1 1
2 2
3 3]
In general repmat does this:
repmat(m, 2, 3);
[m m m
m m m]
% if m=[1 2; 3 4] was the value of m, then
[1 2 1 2 1 2
3 4 3 4 3 4
1 2 1 2 1 2
3 4 3 4 3 4]
Upvotes: 2
Reputation: 8391
I would avoid all these exponentials, taking a log first and then an exp.
% // way cheaper to evaluate
log_KT = log([c1 c2 c3 c4])*KT_coeff(2:end,:);
% // Final exp
KT = KT_coeff(1,:) .* exp(log_KT);
KT = sum(KT);
Upvotes: 0
Reputation: 16193
Try ...
KT = KT_coeff(1,1:37) .* const1.^KT_coeff(2,1:37) .* const2.^KT_coeff(3,1:37) .* const3.^KT_coeff(4,1:37) .* const4.^KT_coeff(5,1:37);
Given that you know the size of each KT_coeff is 37 in the 2nd dimension, you could simplify this a bit further with by replacing 1:37
with just :
above.
Upvotes: 0