subtracting a particular value until that the result becomes negative

5 vues (au cours des 30 derniers jours)
Nikolas Spiliopoulos
Nikolas Spiliopoulos le 22 Fév 2017
Modifié(e) : dpb le 22 Fév 2017
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 commentaires
Adam
Adam le 22 Fév 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.
Nikolas Spiliopoulos
Nikolas Spiliopoulos le 22 Fév 2017
good to know,
i would be grateful If you could tell me how
thanks!

Connectez-vous pour commenter.

Réponse acceptée

Jan
Jan le 22 Fév 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

Plus de réponses (1)

dpb
dpb le 22 Fév 2017
Modifié(e) : dpb le 22 Fév 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 commentaires
Bas Holten
Bas Holten le 22 Fév 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 le 22 Fév 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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by