Improving the speed!

1 visualizzazione (ultimi 30 giorni)
Susan
Susan il 1 Mag 2019
Commentato: Susan il 1 Mag 2019
Hey MATLAB guys,
Could someone please tell me how I can improve this code. It works pretty quick for nt_L=1:3. But, as nt_L increases, it takes forever. Any idea would be greatly appreciated.
K = 10;
nbrOfSubCarriers = 2*ones(1, K);
nt_L = 10;
nr_L = 3*ones(1, nt_L);
ulim_c = 1; % max value of each element
llim_c = 0; % min value of each element
sumlim_c = 1;
c0 = zeros(max(nr_L(:)), numel(nr_L), numel(nbrOfSubCarriers), max(nbrOfSubCarriers(:)));
for k = 1 : K
for m = 1 : nbrOfSubCarriers(k)
RMat = rand(max(nr_L(:)), numel(nr_L))*(ulim_c-llim_c) + llim_c;
Rsum = sum(RMat(:));
Rcheck = Rsum > sumlim_c;
while any(Rcheck)
RMat = rand(max(nr_L(:)), numel(nr_L))*(ulim_c-llim_c) + llim_c;
Rsum = sum(RMat(:));
Rcheck = Rsum > sumlim_c;
end
if Rsum <= sumlim_c
c0(:,:,k,m) = RMat;
else
c0(:,:,k,m) = RMat ./ Rsum; %makes the sum exactly 1
end
end
end

Risposta accettata

gonzalo Mier
gonzalo Mier il 1 Mag 2019
I love this kind of problems. First of all, Matlab comes with a debugger that tell you in which part you are losing your time (It's called Run and Time). After running it, it says that the while loop is really slow, so you have to search one way to make the condition succesful in the first attemp. I have try a solution with some other modifications like the if condition which is achieve by the while.
tic
K = 10;
mult_nbrOfSubCarriers = 2;
nbrOfSubCarriers = mult_nbrOfSubCarriers*ones(1, K);
nt_L = 10;
nr_L = 3*ones(1, nt_L);
ulim_c = 1; % max value of each element
llim_c = 0; % min value of each element
sumlim_c = 1;
max_nr_L = max(nr_L(:));
numel_nr_L = numel(nr_L);
c0 = zeros(max_nr_L, numel_nr_L, K, mult_nbrOfSubCarriers);
sumlim_c2 = (sumlim_c - llim_c)/(ulim_c-llim_c);
for k = 1 : K
for m = 1 : nbrOfSubCarriers(k)
RMat = rand(max_nr_L, numel_nr_L);
sum_RMat = sum(RMat(:));
if sum_RMat > sumlim_c2
RMat = RMat./sum_RMat.*sumlim_c2;
end
c0(:,:,k,m) = RMat.*(ulim_c-llim_c) + llim_c;
end
end
toc
  1 Commento
Susan
Susan il 1 Mag 2019
Thank you sooooooo much! I like the way you have improved my code. Thanks again

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Programming in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by