stop the data comprising from 4 different loops in an array

Hi here is the code :
%%%%%%
for w=[0.01,0.1,0.3,0.8,3]
for K=4:9
for T=2:3
for tau=1:2
G=K*exp(-(tau*(i*w)))/(T*i*w+1);
G_n=6.5/((2.5*(i*w)+1)*(1.5*(i*w)+1));
Delta_a=G-G_n;
%%%%%%%
I want to have Delta_a consisting from an array covering all the values not the very last one Thanks

 Risposta accettata

Guillaume
Guillaume il 20 Dic 2016
Modificato: Guillaume il 20 Dic 2016
You could modify your loops in order to create indices for your Delta_a:
w = [0.01,0.1,0.3,0.8,3];
K = 4:9;
T = 2:3;
tau = 1:2;
Delta_a = zeros(numel(w), numel(K), numel(T), numel(tau)); %predeclare array to avoid growing it in the loop
for wi = 1:numel(w)
for ki = 1:numel(K)
for ti = 1:numel(T)
for taui = 1:numel(tau);
G = K(ki)*exp(-(tau(taui)*(i*w(wi))))/(T(ti)*i*w(wi)+1);
G_n = 6.5/((2.5*(i*w(wi))+1)*(1.5*(i*w(wi))+1));
Delta_a(wi, ki, ti, taui) = G-G_n;
end
end
end
end
Or you could just no bother with the loops, and do it all in one go. It's very easy, particularly if you have R2016b:
w = [0.01,0.1,0.3,0.8,3].'; %column vector
K = 4:9; %row vector
T = permute(2:3, [1 3 2]); %vector along 3rd dimension
tau = permute(1:2, [1 4 3 2]); %vector along 4th dimension
G = K .* exp(-(tau.*1i.*w)) ./ (T.*1i.*w + 1);
G_n = 6.5 ./ ((2.5*1i*w + 1) .* (1.5*1i*w+1));
Delta_a = G - G_n;
Prior to R2016b, you have to use bsxfun:
G = bsxfun(@times, K, exp(-bsxfun(@rdivide, bsxfun(@times, tau, 1i*w), bsxfun(@times, T, 1i*w) + 1)));
G_n = 6.5 ./ ((2.5*1i*w + 1) .* (1.5*1i*w+1));
Delta_a = G - G_n;

Più risposte (1)

Jan
Jan il 20 Dic 2016
Modificato: Jan il 20 Dic 2016
wv = [0.01,0.1,0.3,0.8,3];
Kv = 4:9;
Tv = 2:3;
tauv = 1:2;
Delta_a = zeros(numel(wv), numel(Kv), numel(Tv), numel(tauv)); % Pre-allocate
for iw = 1:numel(w)
w = wv(iw);
G_n = 6.5/((2.5*(1i*w)+1)*(1.5*(1i*w)+1)); % 1i instead of i
for iK = 1:numel(Kv)
K = Kv(iK);
for iT = 1:numel(Tv)
T = Tv(iT);
for itau = 1:numel(tauv)
tau = tauv(itau);
G = K*exp(-(tau*(1i*w)))/(T*1i*w+1);
Delta_a(iw, iK, iT, itau) = G-G_n;
end
end
end
"i" is confuced with the imaginary unit too often, so use 1i instead.

Community Treasure Hunt

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

Start Hunting!

Translated by