How to store the output of a loop in a matrix/vector when the loop is not indexed?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Laura Ramirez
am 29 Mai 2014
Bearbeitet: Andrei Bobrov
am 29 Mai 2014
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 :)
0 Kommentare
Akzeptierte Antwort
Andrei Bobrov
am 29 Mai 2014
Bearbeitet: Andrei Bobrov
am 29 Mai 2014
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)));
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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!