Vectorization of MATLAB/Octave loop -
Vectorization of MATLAB/Octave loop -
can for-loop vectorized further?
for = 1:length(formula) ttable(i,abs(formula(i,:))) = -1*formula(i,:); end where formula matrix , ttable = nan(length(formula),max(max(abs(formula)))). thanks!
judging code, doing each row of ttable, wish utilize indices accessed abs(formula(i,:)) , set each of these locations -1*formula(i,:).
noting @divakar's clever spot, going assume each row has unique absolute values. in other words, each row should not have instances have a or -a in row, a number 1 size(formula,2). reason why because in computation of abs(formula(i,:)), -a , a map same column. conflict , allow overwriting same entry (thanks @divakar!)
what can each row of formula, convert these locations column-major indices access ttable. after, assign corresponding values of -1*formula ttable. in other words:
%// find columns should accessed columnindices = reshape(abs(formula).', 1, []); %// each column accessing, find corresponding row rowindices = reshape(repmat(1:size(formula,2), size(formula, 1), 1), 1, []); %// find column major indices need access overall indices = sub2ind(size(formula), rowindices, columnindices); %// take indices have computed above, , map them %// columns found before ttable(indices) = -1*formula.'; here little test created. based on same assumption of unique absolute values made before:
formula = [1 2 -3 4; 4 -2 3 1; 3 2 4 -1; -4 1 2 3]; ttable = nan(length(formula),max(max(abs(formula)))); formula = 1 2 -3 4 4 -2 3 1 3 2 4 -1 -4 1 2 3 ttable = nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan using approach, get:
for = 1:length(formula) ttable(i,abs(formula(i,:))) = -1*formula(i,:); end ttable = -1 -2 3 -4 -1 2 -3 -4 1 -2 -3 -4 -1 -2 -3 4 using approach, get:
columnindices = reshape(abs(formula).', 1, []); rowindices = reshape(repmat(1:size(formula,2), size(formula, 1), 1), 1, []); indices = sub2ind(size(formula), rowindices, columnindices); ttable(indices) = -1*formula.'; ttable = -1 -2 3 -4 -1 2 -3 -4 1 -2 -3 -4 -1 -2 -3 4 if matrix small, computational overhead doing instead of for loop may larger , inefficient. however, if matrix larger, code may faster. either way, think for loop approach still good. jit should kick in for loops. if take @ post here when doing timing tests algorithm for loop used 1 of algorithms, for loop 1 of algorithms fastest. check here: matlab: subtracting matrix subsets specific rows
matlab octave vectorization
Comments
Post a Comment