vectorization - Vectorize MATLAB code -
let's have 3 m-by-n matrices of equal size: a
, b
, c
.
every column in c
represents time series.
a
running maximum (over fixed window length) of each time series in c
.
b
running minimum (over fixed window length) of each time series in c
.
is there way determine t
in vectorized way?
[nrows, ncols] = size(a); t = zeros(nrows, ncols); row = 2:nrows %loop on rows (except row #1). col = 1:ncols %loop on columns. if c(row, col) > a(row-1, col) t(row, col) = 1; elseif c(row, col) < b(row-1, col) t(row, col) = -1; else t(row, col) = t(row-1, col); end end end
this i've come far:
t = zeros(m, n); t(c > circshift(a,1)) = 1; t(c < circshift(b,1)) = -1;
well, trouble dependency else part of conditional statement. so, after long mental work-out, here's way summed vectorize hell-outta everything.
now, approach based on mapping. column-wise runs or islands of 1s
corresponding 2d
mask else
part , assign them same tags. then, go start-1
along each column of each such run , store value. finally, indexing each such start-1
tagged numbers, work mapping indices give elements set in new output.
here's implementation fulfill aspirations -
%// store sizes [m1,n1] = size(a); %// masks corresponding 3 conditions mask1 = c(2:nrows,:) > a(1:nrows-1,:); mask2 = c(2:nrows,:) < b(1:nrows-1,:); mask3 = ~(mask1 | mask2); %// mask3 set values output out = [zeros(1,n1) ; mask1 + (-1*(~mask1 & mask2))]; %// proceed if element in mask3 set if any(mask3(:)) %// row vectors appending onto matrices matching sizes mask_appd = false(1,n1); row_appd = zeros(1,n1); %// 2d mapped indices df = diff([mask_appd ; mask3],[],1)==1; cdf = cumsum(df,1); offset = cumsum([0 max(cdf(:,1:end-1),[],1)]); map_idx = bsxfun(@plus,cdf,offset); map_idx(map_idx==0) = 1; %// extract values used setting new places a1 = out([df ; false(1,n1)]); %// map indices obtained earlier , set @ places mask3 newval = [row_appd ; a1(map_idx)]; mask3_appd = [mask_appd ; mask3]; out(mask3_appd) = newval(mask3_appd); end
Comments
Post a Comment