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

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 件のコメント

Adam
Adam 2016 年 8 月 9 日
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.

サインインしてコメントする。

 採用された回答

Sean de Wolski
Sean de Wolski 2016 年 8 月 9 日

0 投票

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)

1 件のコメント

Alexandre C Borges
Alexandre C Borges 2016 年 8 月 9 日
That's great! Exactly what I was trying to do. Thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by