Suggestions on how to optimize this code (avoid for-loop)?

1 view (last 30 days)
Hello,
My code organizes data (USD) from a table (tableA) into a 3D matrix (matrixA) using a for-loop. The resulting matrix (matrixA) is as follows:
1st dimension: country 2nd dimension: time 3rd dimension: product
Here's an example:
% CREATE TABLE
product = {'LON';'LON';'LON';'GUA';'GUA'};
country = {'US';'AU';'CA';'US';'CA'};
dt = datetime({'06/30/2016';'03/31/2016';'12/31/2016';'06/30/2016';'03/31/2016'});
USD = [150;200;100;50;75];
tableA = table(product,country,dt,USD);
clear product country dt USD
% VECTORS
products = {'LON';'GUA'};
countries = {'US';'CA';'AU'};
t = datetime('12/31/2015') + calquarters(0:1:4);
% CREATE MATRIX A
matrixA = zeros(3,4,2);
for i = 1:3
for j = 1:2
for k = 1:4
A = ismember(tableA.country,countries(i)) & ...
ismember(tableA.product,products(j)) & ...
gt(tableA.dt,t(k)) & le(tableA.dt,t(k+1));
B = tableA.USD(A);
matrixA(i,k,j) = sum(B);
end
end
end
clear A B i j k
I would appreciate any help on how to do this without a for-loop. Many thanks!!!
  1 Comment
Adam
Adam on 9 Aug 2016
Have you run the profiler on it to check that the for loops are the bottleneck?
I had a function recently in which I was clearing some variables mid-function (it was code I wrote 8 years ago!) which seemed harmless and helpful, but when I ran the profiler on the function the one line clearing variables was taking over 50% of the time of the whole function.

Sign in to comment.

Accepted Answer

Sean de Wolski
Sean de Wolski on 9 Aug 2016
This does what you want but does not order based on your country/product order that you have hardwired but rather based on uvp, uvc, the first output of unique. The corresponding rows/columns are correct.
[uvp,~,idxp] = unique(tableA.product)
[uvc,~,idxc] = unique(tableA.country)
idxdt = discretize(datenum(tableA.dt),datenum(t))
matrixB = accumarray([idxc idxdt idxp],tableA.USD)

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!