Suggestions on how to optimize this code (avoid for-loop)?
Mostra commenti meno recenti
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 Commento
Adam
il 9 Ago 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.
Risposta accettata
Più risposte (0)
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!