Improving the speed!

조회 수: 2 (최근 30일)
Susan
Susan 2019년 5월 1일
댓글: Susan 2019년 5월 1일
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

채택된 답변

gonzalo Mier
gonzalo Mier 2019년 5월 1일
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
Susan
Susan 2019년 5월 1일
Thank you sooooooo much! I like the way you have improved my code. Thanks again

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Calculus에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by