Matlab求第一个负数的级数
使用Matlab中的数字矩阵,如何找到一系列正数之后的第一个负数 到目前为止,我能想到的唯一答案是写一个循环来检查第一个负数,然后记录它,然后查找第一个正数,在那里截断数组,然后重新开始。有没有矢量化的方法可以做到这一点Matlab求第一个负数的级数,matlab,vectorization,Matlab,Vectorization,使用Matlab中的数字矩阵,如何找到一系列正数之后的第一个负数 到目前为止,我能想到的唯一答案是写一个循环来检查第一个负数,然后记录它,然后查找第一个正数,在那里截断数组,然后重新开始。有没有矢量化的方法可以做到这一点 e、 例如,我有x=[-1-5-2 3 4 8-2-3 1 9],我希望这个函数或脚本给我一个y=[1 7]的数组。这是一个相当自制的解决方案,请查看它 x = [ -1 -5 -2 3 4 8 -2 -3 1 9] neg_idx = find(x < 0)
e、 例如,我有x=[-1-5-2 3 4 8-2-3 1 9],我希望这个函数或脚本给我一个y=[1 7]的数组。这是一个相当自制的解决方案,请查看它
x = [ -1 -5 -2 3 4 8 -2 -3 1 9]
neg_idx = find(x < 0) % // negative values
z = [0 diff(neg_idx)] % // increments among indices of successive values;
% // consecutive indices return a difference of 1 whereas
% // non consecutive return a value greater than 1.
% // because the first element must be distinguished
% // we put the zero in front
id = find(z ~= 1) % // Every time there is a jump, a non consecutive neg.
% // value appears
% // thus the solution is in
y = neg_idx(id)
ans =
1 7
如果neg_idx为空,即不涉及负值,则会得到一个超过矩阵维数的索引,尽管该条件需要立即检查。这是一个相当自制的解决方案,请检查它
x = [ -1 -5 -2 3 4 8 -2 -3 1 9]
neg_idx = find(x < 0) % // negative values
z = [0 diff(neg_idx)] % // increments among indices of successive values;
% // consecutive indices return a difference of 1 whereas
% // non consecutive return a value greater than 1.
% // because the first element must be distinguished
% // we put the zero in front
id = find(z ~= 1) % // Every time there is a jump, a non consecutive neg.
% // value appears
% // thus the solution is in
y = neg_idx(id)
ans =
1 7
如果neg_idx为空,即不涉及负值,则会得到一个索引超出矩阵维度,尽管该条件需要立即检查。或
find(diff(sign([1 x]))<0)
也就是说:在x中找到连续元素间符号差为负值的位置,哦,然后在x的前面推1,以处理第一个元素已经为负值的情况或
find(diff(sign([1 x]))<0)
也就是说:在x中找到连续元素间符号差为负的位置,然后将1推到x的前面,以处理第一个元素已经为负的情况