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

조회 수: 1 (최근 30일)
Alexandre C Borges
Alexandre C Borges 2016년 8월 9일
댓글: Alexandre C Borges 2016년 8월 9일
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일
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)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by