How to remove/add elements to an array?
显示 更早的评论
Hi All,
I have a 115x1 vector, say A which is attached, that I'd like to remove the elements that satisfy some conditions and add some that satisfy others. To be specific,
B = diff(A) = [768 12 757 767 12 756 ...1524.....768 13 754 271]
if B(n)<100, I would like to remove A(n) from A.
if 100 < B(n) < 300, I would like to remove A(n+1) from A.
if B(n) > 1500, I'd like to add an element to A between two elements of A that their diff value satisfies this constraint. for example B(91)=1523, and I like to add a point between A(91) and A(92), i.e., A(91)+A(92)/2.
I know how to do that when there is one constraint, but I struggle when there are more. Any help would be greatly appreciated.
pointToDelet = B<100;
A(pointToDelet) = []
采纳的回答
更多回答(1 个)
millercommamatt
2022-12-13
编辑:millercommamatt
2022-12-13
% B = diff(A) = [768 12 757 767 12 756 ...1524.....768 13 754 271]
% note that B will be one less in length than A
% if B(n)<100, I would like to remove A(n) from A.
A_FilteredOnB = A(1:end-1);
A_FilteredOnB = A_FilteredOnB(B>=100);
% if 100 < B(n) < 300, I would like to remove A(n+1) from A.
A_FilteredOnB_again = A(2:end); % note the difference from before
A_FilteredOnB_again = A_FilteredOnB_again(B >= 100 & B <= 300);
% if B(n) > 1500, I'd like to add an element to A between two elements
% of A that their diff value satisfies this constraint. for example B(91)=1523,
% and I like to add a point between A(91) and A(92), i.e., A(91)+A(92)/2.
% This one is tricky.
inds = find(B>1500);
for ii = inds
A = [A(1:ii), (A(ii)+A(ii+1))/2, A(ii+1:end)];
end
2 个评论
@millercommamatt: What happens when B has two elements in a row > 1500?
A = [0 1600 3400];
B = diff(A);
inds = find(B>1500);
for ii = inds
A = [A(1:ii), (A(ii)+A(ii+1))/2, A(ii+1:end)];
end
A
Doesn't seem right. That's because when you insert the new element, all the higher indices (i.e., the rest of the elements of inds) are now one lower than they need to be, to account for the new element just inserted.
If you start at the end and go backwards instead, it works:
A = [0 1600 3400];
B = diff(A);
inds = find(B>1500);
for ii = inds(end:-1:1)
A = [A(1:ii), (A(ii)+A(ii+1))/2, A(ii+1:end)];
end
A
millercommamatt
2022-12-13
this is why you test code
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
