我有一个二进制数组,我想根据它们重复的长度来翻转值。作为一个例子
add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 20 );
add_action( 'woocommerce_account_dashboard', 'account_custom_area', 1 );
function account_custom_area () {
$blendiclubtitle = the_field('blendi_club_title', 'option') ;
$blendiclubcontent = the_field('blendi_club_content', 'option') ;
echo "<h2>" . $blendiclubtitle . "</h2>";
echo "<p class='blendi_club_content'>" . $blendiclubcontent . "</p>";
};
理想情况下,我想翻转仅重复2次或更少次数的1,导致以下情况。
Ar = [0 1 0 0 0 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1];
答案 0 :(得分:5)
只需使用图像处理工具箱中的imopen
,内核为3
ones
-
imopen(Ar,[1,1,1])
示例运行 -
>> Ar = [0 1 0 0 0 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1];
>> out = imopen(Ar,[1,1,1]);
>> [Ar(:) out(:)]
ans =
0 0
1 0
0 0
0 0
0 0
1 0
1 0
0 0
0 0
0 0
1 1
1 1
1 1
1 1
1 1
0 0
0 0
0 0
0 0
1 1
1 1
1 1
1 1
1 1
1 1
不使用I.P.的矢量化解决方案工具箱 -
function out = filter_islands_on_length(Ar, n)
out = Ar;
a = [0 Ar 0];
d = diff(a);
r = find(d);
s0 = r(1:2:end);
s1 = r(2:2:end);
id_arr = zeros(1,numel(Ar));
m = (s1-s0) <= n;
id_arr(s0(m)) = 1;
id_arr(s1(m)) = -1;
out(cumsum(id_arr)~=0) = 0;
样品运行 -
>> Ar
Ar =
0 1 0 0 0 1 1 0 0 0 1 1 1
>> filter_islands_on_length(Ar, 2)
ans =
0 0 0 0 0 0 0 0 0 0 1 1 1
>> filter_islands_on_length(Ar, 1)
ans =
0 0 0 0 0 1 1 0 0 0 1 1 1
答案 1 :(得分:2)
另一个不需要工具箱但需要Matlab 2016a或更高版本的解决方案:
n = 3; % islands shorter than n will be removed
Ar = movmax(movsum(Ar,n),[ceil(n/2-1) floor(n/2)])==n;