我有一个看起来像这样的数组:
20 1
20 7
45 3
127 17
102 1
90 1
64 1
等...左侧列显示光强度值,右侧列显示它出现的次数。我想要一个扩展数组的相应单元格数组,并单独列出每个值的次数。像这样(忽略左侧单元格列):
[] 20
[] 20
[] 20
[] 20
[] 20
[] 20
[] 20
[] 20
[] 45
[] 45
[] 45
等等......谁可以告诉我一个明智的做法?棘手的索引在这里。我有以下笨拙的作品(种类)有效:
% Determine the number of 10-minute intervals for which a light level is
% recorded (sum all the unique light levels and their repeats).
no_light_levels = sum(repeat_arr(:, 2));
%
% 'geologger_data_all' records time of each light level reading and the
% light level.
geologger_data_all{no_light_levels, 2} = [];
geologger_data_all(1, 2) = {repeat_arr(1, 1)};
%
k_out = 2; % index for out arr.
for k = 2:length(repeat_arr)
light_level = repeat_arr(k, 1); % grab the light level
appears = repeat_arr(k, 2); % does it repeat?
if appears == 1
geologger_data_all(k_out, 2) = {light_level}; % record
k_out = k_out + 1;
elseif appears > 1
% Record the light level for the number of times it appears.
geologger_data_all(k_out:(k_out + appears - 1), 2) = {light_level};
k_out = k_out + appears; % advance index for out arr.
end
end
%
repeat_arr
看起来像这里显示的第一个格式化数组。提前感谢任何提示。
答案 0 :(得分:4)
您所拥有的内容run-length-encoded data可以使用repelem
解码,并按指定的次数重复每个元素
data = [20 1;20 7;45 3;127 17;102 1;90 1;64 1];
out = repelem(data(:,1), data(:,2))
如果你真的需要像你所展示的那样制作一个单元格数组,你可以添加以下步骤:
result(:,2) = num2cell(out);
如果您使用的是早于R2015a的MATLAB版本(在引入repelem
之前),您可以使用提供的解决方案here来获得类似的功能。