How to store the output of a loop in a matrix/vector when the loop is not indexed?

조회 수: 1 (최근 30일)
Hi everyone, I'm new in matlab and i need to store the output of a loop in a vector. the problem is that the loop is not indexed therefore i cannot create a vector of zeros where to store the output. My code looks as follows
a=-1;
b=-1;
p=-0.5;
a1 = a./sqrt(2*(1-p^2));
b1 = b./sqrt(2*(1-p^2));
for xj = [0.10024215,0.48281397,1.0609498,1.7797294,2.6697604];
xi = [0.10024215,0.48281397,1.0609498,1.7797294,2.6697604]';
f1 = sum(exp( a1.*(2*xi - a1) + b1.*(2*xj-b1) + 2*p.*(xi-a1).*(xj-b1)))
end
and my output looks as follows
f1 =
0.121232883313475
f1 =
0.043069611850309
f1 =
0.009189704089853
f1 =
0.001377436854364
f1 =
1.344664406705558e-
I need to store that in a vector. Could somebody please tell me what's the correct way to do it ? Thaanks :)

채택된 답변

Andrei Bobrov
Andrei Bobrov 2014년 5월 29일
편집: Andrei Bobrov 2014년 5월 29일
a=-1;
b=-1;
p=-0.5;
a1 = a./sqrt(2*(1-p^2));
b1 = b./sqrt(2*(1-p^2));
x = [0.10024215,0.48281397,1.0609498,1.7797294,2.6697604];
[xi,xj] = ndgrid(x);
f1 = sum(exp( a1.*(2*xi - a1) + b1.*(2*xj-b1) + 2*p.*(xi-a1).*(xj-b1)));
with use bsxfun
f1 = sum(exp(...
bsxfun(@plus,a1*(2*x(:)-a1),b1*(2*x(:)'-b1)) + 2*p*(x(:)-a1)*(x(:)'-b1)),2);
or with loop for..end
n = numel(x);
f1 = zeros(n,1);
f = zeros(n);
for jj = 1:n
for ii = 1:n
f(ii,jj) = exp(a1.*(2*x(ii) - a1)...
+ b1.*(2*x(jj)-b1) + 2*p.*(x(ii)-a1).*(x(jj)-b1));
end
f1(jj) = sum(f(:,jj));
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by