subtracting a particular value until that the result becomes negative

5 views (last 30 days)
Hi all,
how can I subtract elements of a column until the point that the result is negative?
example: A=[1 2 3 4 5 4 2 1 1 1 3]' , I have an external value let's say 6. I want to go to the 6th element lets say and do this:6-4. then take the result (in this case 2), and subtract it from the next element until the result to become negative. At this point I would like to stop the process. is there any way to do this?
Imagine that I have an array 48X365
thanks!
  10 Comments
Adam
Adam on 22 Feb 2017
It seems like there is surely an easier way to represent the problem than this!
You could just do it in a basic for loop though I would have thought.

Sign in to comment.

Accepted Answer

Jan
Jan on 22 Feb 2017
And another guess:
A = [1 2 3 4 5 4 2 1 1 1 3]'
x = 8;
for index = 6:length(A) % Start at 6th element
x = x - A(index);
A(index) = x;
if x < 0
break;
end
end

More Answers (1)

dpb
dpb on 22 Feb 2017
Edited: dpb on 22 Feb 2017
>> A =[1:5 4 2 1 1 1 3];
>> ix=6; % initial location
>> v=8; % external initial value
>> dA=v-A(ix); % first try
>> while dA>=0
ix=ix+1;
dA=dA-A(ix)
end
dA =
2
dA =
1
dA =
0
dA =
-1
>> ix
ix =
10
>>
Don't know what you intend re: the "have an array 48X365" and, of course, there's the issue of ix running off the end of the array if the while condition isn't satisfied so either need to be certain that there is a solution or have a bounds check.
  3 Comments
Bas Holten
Bas Holten on 22 Feb 2017
'ix' is de index in your array and is still undefined the first time you use it in the code above. Just state at the start* that
ix = 1;
*Assuming you want to start at the first element of the array.
dpb
dpb on 22 Feb 2017
As Bas says, it's that initial point; was 6 in your example. I missed it in the cut'n paste. Fixed in answer.

Sign in to comment.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!