MATLAB Answers

Translated by

このページのコンテンツは英語から自動翻訳されています。自動翻訳をオフにする場合は「<a class="turn_off_mt" href="#">ここ</a>」をクリックしてください。

0

Counting the number of elements of a vector found between a range in another vector

Hari krishnan さんによって質問されました 2018 年 12 月 6 日
最新アクティビティ Guillaume
さんによって 回答されました 2018 年 12 月 7 日
I have a column which contains a range of values in a column 'Range' and another vector containing specific values in a column 'entryTime'. How to output the number of elements found in column 'entryTime' within the column 'Range'.
Data is attached

  0 件のコメント

サインイン to comment.

2 件の回答

回答者: Guillaume
2018 年 12 月 7 日
 採用された回答

Frankly, the way you've stored your data is rubbish and making your work much harder.
Firstly, Your ranges shouldn't be stored as char arrays. It should be a 2 x numranges matrix or table.
Secondly, since the rows of Range have absolutely nothing to do with the rows of entryTime, they shouldn't be stored together in the same table. That would avoid pointless storing nans in entryTime if there are more ranges or god knows what as a filler in Ranges if there are more entryTimes.
So let's fix this:
ranges = regexp(data.Range, '([^-]+)-(.+)', 'tokens', 'once'); %plenty of other ways to split the data
ranges = array2table(str2double(vertcat(ranges{:})), 'VariableNames', {'lowerbound', 'upperbound'})
entryTimes = data(:, 'entryTime');
entryTimes(isnan(entryTimes.entryTime), :) = []
Then your problem is trivial:
rangecount = rowfun(@(l, u) sum(entryTimes.entryTime >= l & entryTimes.entryTime <= u), ranges, 'OutputVariableNames', {'count'})

  0 件のコメント

サインイン to comment.


回答者: TADA
2018 年 12 月 6 日
編集済み: TADA
2018 年 12 月 6 日

If you keep your range data as two columns instead of strings you can easily do it
et = data.entryTime(~isnan(data.entryTime));
% split ranges by '-' character
rng = cellfun(@(str) strsplit(str, '-'), data.Range, 'UniformOutput', false);
% Unravel cell array and parse numbers
ranges = str2double(vertcat(rng{:}));
% find which entry times are within any of the ranges
entryTimesInRangeMask = arrayfun(@(t) any(t >= ranges(:,1) & t <= ranges(:,2)), et);
% output number of elements within any of the ranges
disp(['Number of entry times within range: ' num2str(sum(entryTimesInRangeMask))]);

  1 件のコメント

@TADA thank you very much. But this will give me the toral numbers of elements which falls between all the ranges. What i want to do is to calculate the number of elements in each independent range.
for eg: range = [0:5; 5.1:10; 10.1:15]
entries = [1, 2, 3, 4, 5, 11, 12]
Expected output: Number of entries in range "0:5" = 5
Number of entries in range "5.1:10" = 0
Number of entries in range "10.1:15" = 2

サインイン to comment.



Translated by