How can I create a nested loop without confusing the indeces?
Afficher commentaires plus anciens
I have the following problem:
a variable x(i) that represents the payoff and its value changes as other variables cgange WHILE I KEEP FIXED alpha. So I can get it by using a simple loop like that
alpha = 0.3; % between 0 and 1
x = zeros(N,1);
for i=1:N
x(i) = alpha*exp(z(i))+(1-alpha)*exp(u(i));
end
I don't know how to get different paths of x(i) as alpha changes
Réponses (1)
Let's see if I understand the intent... I don't know what z and u are, so I'm just going to use placeholders.
N = 10;
alpha = [0.2 0.3 0.5]; % a vector of alpha
z = rand(N,1);
u = rand(N,1);
x = alpha.*exp(z) + (1-alpha).*exp(u)
Note that alpha and the other vectors are orthogonal. Implicit array expansion allows the expression to be evaluated for all values of the parameter alpha (one column each).
3 commentaires
Federica Fubelli
le 30 Sep 2021
Image Analyst
le 30 Sep 2021
DGM showed you the vectorized way, not recursive. However you can make up a function that takes alpha as in input if you want. However you'd just call it as you need to (with the new alpha) -- you don't need to call the function recursively, and you should not.
That's what the example does. I don't see the functional difference between doing the operations sequentially or simultaneously. For demonstration:
% SETUP
N = 10;
alpha = [0.2 0.3 0.5]; % a vector of alpha
z = rand(N,1);
u = rand(N,1);
% USING LOOPS
x = zeros(N,numel(alpha));
for ia = 1:numel(alpha)
for ix = 1:N
x(ix,ia) = alpha(ia)*exp(z(ix)) + (1-alpha(ia))*exp(u(ix));
end
end
% USING VECTORIZED MATH
x2 = alpha.*exp(z) + (1-alpha).*exp(u);
immse(x,x2) % show that the results are identical
Perhaps instead z and u are larger than you want the output to be, and you only want to sample a portion of them.
% SETUP
N = 10;
alpha = [0.2 0.3 0.5]; % a vector of alpha
z = rand(100,1); % larger than N
u = rand(100,1);
% USING LOOPS
x = zeros(N,numel(alpha));
for ia = 1:numel(alpha)
for ix = 1:N
x(ix,ia) = alpha(ia)*exp(z(ix)) + (1-alpha(ia))*exp(u(ix));
end
end
% USING VECTORIZED MATH
x2 = alpha.*exp(z(1:N)) + (1-alpha).*exp(u(1:N));
immse(x,x2) % show that the results are identical
There is the possibility that you want x to remain a vector, and that each evaluation for alpha should simply be concatenated to the end. In that case, just do this to the result:
x = x(:);
% or
x = reshape(x,[],1);
That will reshape the multicolumn output into a single column vector.
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!