使用 MATLAB,您可以使用逻辑索引,这意味着您可以使用任意数量的条件过滤变量。例如,如果vec
是任何向量并且您想知道有多少元素vec
是负数,您可以执行以下操作,
% save the elements of vec which are negative
ind = vec < 0
% vec is a logical variable. Each element of vec lower that 0 is store as 1.
% to know how many elements of vec are smaller than 0
sum(ind)
% will tell you how many ones are there in ind, meaning the number of elements in vec which
% are smaller than 0
% Of course you can do the same all at once,
sum(vec < 0)
% and you can directly access the elements in the same way
vec(vec < 0)
所以回到你的问题,你可以使用类似的东西,
for i = 1:3:length(A)
%print how many 2s,3s and 4s
fprintf('%d to %d: %d, %d, %d\n',i,i+2,sum(A(i:i+2,2)==2),sum(A(i:i+2,2)==3),sum(A(i:i+2,2)==4))
end