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

 Respuesta aceptada

Walter Roberson
Walter Roberson el 7 de Oct. de 2017
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.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 7 de Oct. de 2017

Comentada:

el 7 de Oct. de 2017

Community Treasure Hunt

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

Start Hunting!

Translated by