MATLAB: Store vectors from a for loop in a matrix

for loop

I have this function
for ci=0.0001:0.5:(2*alt_Col)
Esi=0.003*((ci-di)/(ci))
end
where di is a column vector. How do I store all the Esi vector in a matrix? Thanks in advance

Best Answer

You can use the following pattern when you are using a for loop over a range of non-integral values:
ci_vals = 0.0001:0.5:(2*alt_Col);
num_ci = length(ci_vals);
num_di = length(di);
Esi = zeros(num_ci, num_di);
for ci_idx = 1 : num_ci;
ci = ci_vals(ci_idx);
Esi(ci_idx, :) = 0.003*((ci-di) ./ (ci));
end
... Or you could omit the for loop, and use a vectorized approach:
ci = 0.0001:0.5:(2*alt_Col);
Esi = 0.003 * bsxfun(@rdivide, bsxfun(@minus, ci, di), (ci));
Or you could use:
ci = 0.0001:0.5:(2*alt_Col);
[CI, DI] = meshgrid(ci, di);
Esi = 0.003 * ((CI-DI) ./ (CI));
or, in R2016b or later, you can use built-in implicit expansion:
ci = 0.0001:0.5:(2*alt_Col);
Esi = 0.003 * ((ci-di) ./ (ci));
The bxsfun version is a more efficient approach than meshgrid. The implicit expansion version "aims" to be more efficient than the bsxfun but user tests have shown that sometimes the implicit expansion version is slower than the bsxfun version.
Related Question