我需要以下函数的帮助:for循环或矢量化代码中的histc和numel。我有一个可以是任何尺寸的矩阵。代码需要输出元素在一个区间中出现的次数,直到每一行的结尾。因此,对于以下示例,我想要查找在行1中出现数字1的次数。因此在行1中,数字1在被两个0'中断之前出现两次。然后它会在最后一列中再次出现。所以输出将是2 1.
我感谢任何帮助。谢谢
x = hist( data, numel(unique(data)) );
y = histc( data, unique(data) );
data (input) 5x5
1 1 0 0 1
1 1 1 1
0 0 1
0 0 1 1 1
1 0 1 1 1
y (output)
2 1
2 2
1
3
1 3
答案 0 :(得分:1)
假设x
是输入数组,这可能是一种方法 -
[nrows,ncols] = size(x);
new_ncols = ncols + 2;
%// Pad one column of zeros on left and right sides of x
x_pz = [zeros(nrows,1) x zeros(nrows,1)]
%// Flatten padded x
x_pzf = reshape(x_pz',[],1)'
%// Start & end indices of islands of ones for flattened padded x
starts = strfind(x_pzf,[1 0]);
ends = strfind(x_pzf,[0 1])
row_ids = ceil(starts/new_ncols); %// row IDs for each island of ones
%// Start & end indices of islands of ones for flattened non-padded (corrected) x
starts_cor = ends - 2*(row_ids-1)
ends_cor = starts - (2*row_ids-1)
%// Get number of elements in each island of ones
counts = ends_cor - starts_cor + 1
%// Bin row_ids for each row of input array
counts_per_row = histc(row_ids,1:nrows)
%// Now setup output array with conts for each island corresponding to each
%// row ending up in its each row and setting the blank spaces as NaNs
mask = bsxfun(@ge,counts_per_row,(1:max(counts_per_row))') %//'
y = NaN(size(mask))
y(mask) = counts
y = y'
代码运行 -
>> x (modified from the original one to test out more varied situations)
x =
1 1 0 0 1 1
1 1 0 1 1 0
0 0 0 0 1 0
0 0 1 1 1 0
1 0 1 1 1 1
1 1 1 1 1 1
0 0 0 0 0 0
0 1 0 1 0 1
>> y
y =
2 2 NaN
2 2 NaN
1 NaN NaN
3 NaN NaN
1 4 NaN
6 NaN NaN
NaN NaN NaN
1 1 1
如果您正在寻找更直观,更简洁的方法来获取和显示最终输出,您可以使用单元格阵列。所以,你可以这样做 -
>> ycell = arrayfun(@(n) counts(row_ids==n),1:nrows,'Uni',0);
>> celldisp(ycell)
ycell{1} =
2 2
ycell{2} =
2 2
ycell{3} =
1
ycell{4} =
3
ycell{5} =
1 4
ycell{6} =
6
ycell{7} =
[]
ycell{8} =
1 1 1