简体   繁体   中英

Downsampling cell array elements, Matlab

Given a cell array of n elements (n > 1), each element being a 2-d array with x=k number of rows and y columns (variable across cell elements), what would be the best way to down-sample each cell element by randomly removing samples in the y-dim to match the shortest y length across all cell elements?

The snippet below is a mis-implementation and only for n=2, but goes in the right direction (I hope). Any help would be greatly appreciated, thanks!

sizeShortest = min(cellfun('size', data, 2));

sizeLongest = max(cellfun('size', data, 2));
idx = randperm(sizeLongest);
data = cellfun(@(x) x(:,idx(1:sizeShortest)), data, 'UniformOutput', false);

I guess I could use a for loop to go through each cell of the data array and check whether this element has a y length longer than the shortest y of all cells and randomly remove samples. But there's probably a better solution..

Thanks!

This does what you want:

sizeShortest = min(cellfun('size', data, 2));
sizeLongest = max(cellfun('size', data, 2));
f=@(x)(x(:,sort(getfield(randperm(size(x,2)),{1:sizeShortest}))))
data = cellfun(f, data, 'UniformOutput', false);

To explain it.

Generate indices up to the array size, not up to sizeLongest. Otherwise you get index out of bounds:

g=randperm(size(x,2))

Getfield is used to allow double indexing, what should be implemented is:

g(1:sizeShortest)

which means, selects the first indices. sort is put in to use the selected indices in order, and finally based on the indices, the right columns are selected

x(:,sort(...))

Assuming a case of cell array of numerals, you may try this -

%// c1 is input cell array

k = size(c1{1},1)

t1 = cellfun(@size,c1,'uni',0)
t2 = cellfun(@numel,c1)./k

mincols = min(t2)
m1 = (t2-1)./(mincols-1)

p1 = round(bsxfun(@times,0:mincols-1,m1)+1)
p2 = [0; cumsum(t2(1:end-1))]
p3 = reshape(bsxfun(@plus,p1,p2)',[],1) %//'

ha1 = horzcat(c1{:})
g1 = reshape(ha1(:,p3),k,mincols,[])
g2 = reshape(permute(g1,[1 3 2]),size(g1,1)*size(g1,3),[])

out = mat2cell(g2,k*ones(1,numel(c1)),mincols) %// desired downsampled output cell array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM