登录论坛

查看完整版本 : 如何使用MATLAB中的FIND函数计算项目数?


poster
2019-12-10, 20:41
如何使用函数FIND计数给定值的项目数,而不是使用循环?例如,在下面的数组item中,数字23出现3次,数字22出现2次,数字20出现2次。

.... for i=2:n if item(i-1)~=item(i) nItem21(i)=1; else nItem21(i)=nItem21(i-1)+1; end end item Num 23 2 23 4 23 6 22 3 22 1 20 6 20 8

回答:

您可以执行以下操作:确定item的值在哪里更改,然后使用diff获取计数。

item = [ 23 23 23 22 22 20 20]; % find the 'last' entries of each consecutive group of numbers chgRowNum = [find(item(1:end-1) ~= item(2:end);length(item)]; counts = diff([0;chgRowNum]); correspondingItems = item(chgRowNum);

更多&回答... (https://stackoverflow.com/questions/3085429)