Accelerate Matlab calculation for multi-dimension matrix
Mostra commenti meno recenti
I want to solve a problem in space (3-dimensional:x y and z coordinate) and time(t). In general, my problem is like the code below:
A=rand(220);
x=0:1:50;
y=0:1:50;
z=0:1:50;
t=0:1:50;
B=zeros(length(x),length(y),length(z),length(t));
for ix=1:length(x)
for iy=1:length(y)
for iz=1:length(z)
for it=1:length(t)
B(ix,iy,iz,it)=sum(sum(sum(sum((A.*A*x(ix))+((A.^3)*y(iy))+...
((A+2*A)*z(iz))+((A.^4)*t(it))))));
end
end
end
end
However, the looping proccess takes much time. I am afraid i can not use repmat to decrease the computational time since it will need large memory to store the variable. Do you have any suggestion to make the simulation faster?
Thank you very much.
Michael
Risposte (2)
the cyclist
il 24 Mar 2016
0 voti
A 50x50x50x50 array of doubles is only about 48 MB of storage. I see no memory problem in vectorizing the whole calculation.
1 Commento
Michael Lubis
il 24 Mar 2016
Roger Stafford
il 24 Mar 2016
As you have written your code, A is a 2D array and yet you have taken four successive sums, which makes no sense. Either you meant A to be 4D or you meant to have only two successive sums. Either way your code is enormously inefficient. The summation of A.*A, A.^3, A+2*A, and A.^4 can be done just once for each of these four rather than 48,400 separate times each.
I will assume that A is to be 2D and you meant only two sums.
A=rand(220);
x=0:1:50;
y=0:1:50;
z=0:1:50;
t=0:1:50;
A1 = sum(sum(A.^2))*x;
A2 = sum(sum(A.^3))*y;
A3 = sum(sum(3*A))*z;
A4 = sum(sum(A.^4))*t;
B = zeros(51,51,51,51);
for ix = 1:51, for iy = 1:51, for iz = 1:51, for it = 1:51
B(ix,iy,iz,it) = A1(ix)+A2(iy)+A3(iz)+A4(it);
end, end, end, end
This should be much faster than your original code (unless Mathworks' compilers are awfully smart.)
1 Commento
Michael Lubis
il 24 Mar 2016
Categorie
Scopri di più su Resizing and Reshaping Matrices in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!