How to speed up calculation taking inputs from 2 separate and very large matrices (working code below)
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi. The code below works. updated portion the REAL is 'a' is at 10600X5 and and 'b' at 60X5 and takes forever to run. How can I massively speed up the calculation?
*updated*
tic
a = randi([0,100],10600,5) % example only to run the code
b = randi([0,20],60,5)
new = zeros(size(a,1)*size(b,1),size(a,2));
w = 0;
for s= 1:size(a,1)
for t= 1:size(b,1)
new(w+t,:)= [(3*a(s,1)+b(t,1)), (5*a(s,2)+b(t,2)), (1*a(s,3)+b(t,3)), (5*a(s,4)+b(t,4)) , (2*a(s,5)+b(t,5))];
end
w=w+size(b,1);
end
toc
4 commentaires
Jan
le 26 Oct 2018
@klb: Do I understand correctly: The posted code works with the needed speed, but some other code, which you do not show, is much slower? We cannot know the reason of this difference without seeing the other code. So all I can do is to suggest letting the profile find out, where the time is spent.
Réponses (1)
per isakson
le 28 Oct 2018
Modifié(e) : per isakson
le 28 Oct 2018
Try
>> cssm()
Elapsed time is 0.073258 seconds.
Elapsed time is 0.073459 seconds.
Elapsed time is 0.042250 seconds.
Elapsed time is 0.019368 seconds.
ans =
1×3 logical array
1 1 1
where
function cssm()
a = randi([0,100],10800,5); % example only to run the code
b = randi([0,20],60,5);
tic, new1 = cssm_1( a, b ); toc
tic, new2 = cssm_2( a, b ); toc
tic, new3 = cssm_3( a, b ); toc
tic, new4 = cssm_4( a, b ); toc
[ all(new1(:)==new2(:)), all(new1(:)==new3(:)), ll(new1(:)==new4(:)) ]
end
function new = cssm_1( a, b )
%%*updated*
new = zeros(size(a,1)*size(b,1),size(a,2));
w = 0;
for s = 1:size(a,1)
for t = 1:size(b,1)
new(w+t,:)= [(3*a(s,1)+b(t,1)) ...
,(5*a(s,2)+b(t,2)) ...
,(1*a(s,3)+b(t,3)) ...
,(5*a(s,4)+b(t,4)) ...
,(2*a(s,5)+b(t,5)) ];
end
w=w+size(b,1);
end
end
function new = cssm_2( a, b )
new = zeros(size(a,1)*size(b,1),size(a,2));
w = 0;
a = [3,5,1,5,2].*a;
for s = 1:size(a,1)
for t = 1:size(b,1)
new(w+t,:)= [(a(s,1)+b(t,1)) ...
,(a(s,2)+b(t,2)) ...
,(a(s,3)+b(t,3)) ...
,(a(s,4)+b(t,4)) ...
,(a(s,5)+b(t,5)) ];
end
w=w+size(b,1);
end
end
function new = cssm_3( a, b )
new = zeros(size(a,1)*size(b,1),size(a,2));
w = 0;
a = [3,5,1,5,2].*a;
for s = 1:size(a,1)
for t = 1:size(b,1)
new(w+t,:)= a(s,:)+b(t,:);
end
w=w+size(b,1);
end
end
function new = cssm_4( a, b )
new = zeros(size(a,1)*size(b,1),size(a,2));
w = size(b,1);
a = [3,5,1,5,2].*a;
for s = 1:size(a,1)
new( ( 1+(s-1)*w : s*w ), : ) = a(s,:)+b;
end
end
Caveat: I increased 10600 to 10800 to make it a multiple of 60.
0 commentaires
Voir également
Catégories
En savoir plus sur Clocks and Timers dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!