MATLAB: Select all of an array EXCEPT in given ranges

耗尽温柔 提交于 2019-12-01 06:06:52

问题


I'd like to perform metrics on the contents of an array that do NOT fall within certain ranges.

For example, I have an array with 1000 rows and 2 columns. I'd like to perform a mean() calculation on all the elements in one column (let's say column #2) that don't fall in rows 50-150, 250-300, 400-700 and 900-950.

Thus, the mean should be calculated based on rows 1-49, 151-249, 301-399, 701-899 and 951-1000.

Any ideas how to go about this?

Edit: I should point out that those items which are included will change each time the program is run. Therefore, I can't just hard-code the inclusions in; they need to be worked out based on the exclusions.


回答1:


How about:

M = rand(1000,2);
idx = setdiff(1:size(M,1), [50:150, 250:300, 400:700, 900:950]);

MM = M(idx,:)

Now apply any function to the filtered matrix:

mean(MM,1)



回答2:


You can define the exclusion ranges and then use logical addressing:

LowerLimit1 = 1;
UpperLimit1 = 50;

LowerLimit2 = 151;
UpperLimit2 = 249;

LowerLimit3 = 301;
UpperLimit3 = 399;

LowerLimit4 = 701;
UpperLimit4 = 899;

LowerLimit5 = 951;
UpperLimit5 = 1000;

MyVector = MyMatrix(:,2);

MeanValue = mean(MyVector(~(MyVector > LowerLimit1 & MyVector < UpperLimit1) | (MyVector > LowerLimit2 & MyVector < UpperLimit2) |  (MyVector > LowerLimit3 & MyVector < UpperLimit3)  | (MyVector > LowerLimit4 & MyVector < UpperLimit4) | (MyVector > LowerLimit5 & MyVector < UpperLimit5)));


来源:https://stackoverflow.com/questions/11054728/matlab-select-all-of-an-array-except-in-given-ranges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!