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

 채택된 답변

Walter Roberson
Walter Roberson 2017년 10월 7일

1 개 추천

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.

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

질문:

2017년 10월 7일

댓글:

2017년 10월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by