在向量Matlab中检查单元格的邻居 [英] check the neighbours of a cell in a vector Matlab
问题描述
我有两个向量
K=[1 1 1 2 1 2 1 4 2 10 4 5 1]
和
L=[2 0 1 2 1 2 1 3 2 0 1 2 1]
我想将每个向量中的第7个元素的值与该值的邻居进行比较,其中邻居是在每一侧与该元素相邻的5个元素.因此,对于K
,第7个元素是1
,邻居是1 1 1 2 1 2
(左邻居)和4 2 10 4 5 1
(右邻居).
I want to compare the value of the 7th element in each vector with the neighbours of this value, where the neighbours are 5 elements next to this element in each side. So for K
, the 7th element is 1
and the neighbours are 1 1 1 2 1 2
(left neighbours) and 4 2 10 4 5 1
(right neighbours).
对于L
,第7个元素是1
,邻居是2 0 1 2 1 2
(左邻居)和3 2 0 1 2 1
(右邻居).如果第7个值与它的每个邻居之间的差值大于某个阈值,那么我将做某事,例如X = 1,如果不是,那么我将做另一件事,例如X=2
.
For L
, the 7th element is 1
and the neighbours are 2 0 1 2 1 2
(left neighbours) and 3 2 0 1 2 1
(right neighbours). If the difference between the 7th value and each of its neighbours is above a certain threshold then I'll do something e.g X=1, if not then I'll do another thing e.g X=2
.
因此在我的示例中,我将阈值设置为3,因此对于K,第7个元素值是1,并且它与它的两个相邻元素10,5之间的差大于阈值3,所以X将是1 .对于L,第5个元素的值为1,并且它与所有相邻元素之间的差小于阈值3,因此X为2.不知道是否可以不使用循环来节省时间.
So in my example I'll set the threshold to 3, so for K the 7th element value is 1 and the difference between it and two of its neighbours 10,5 are more than the threshold value 3 so X will be 1. For L the 5th element value is 1 and the difference between it and all of its neighbours is less than the threshold value 3 so X will be 2. So I'm wondering if anyone could assist me to do this condition, I'm not sure if this can be done without loops to save time.
推荐答案
您可以使用any
和or
来检查这种情况:
You can check this condition using any
and or
:
N = 5; % reference index
T = 3; % threshold
V = L; % used to pass the vector L to the if-statement
% V = K;
% formulate if-statement to check for values
% below/above index N and check if any difference
% exceeds the threshold
% the or-statement (because it does not matter if the
% threshold is exceeded above index N or below)
% is expressed as |
if any((V(1:N-1)-V(N))>T) | any((V(N+1:end)-V(N))>T)
X = 1;
else
X = 2;
end
注意
取决于您的Matlab版本,V(1:N-1)-V(N)
将不起作用,因为矩阵尺寸不一致.在这种情况下,请使用:V(1:N-1)-ones(size(V(1:N-1))).*V(N)
Note
Depending on your Matlab version V(1:N-1)-V(N)
will not work, because the matrix dimensions do not agree. In this case use: V(1:N-1)-ones(size(V(1:N-1))).*V(N)
这篇关于在向量Matlab中检查单元格的邻居的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!