subtracting a particular value until that the result becomes negative
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Nikolas Spiliopoulos
el 22 de Feb. de 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 comentarios
Adam
el 22 de Feb. de 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.
Respuesta aceptada
Jan
el 22 de Feb. de 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
1 comentario
Más respuestas (1)
dpb
el 22 de Feb. de 2017
Editada: dpb
el 22 de Feb. de 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 comentarios
Bas Holten
el 22 de Feb. de 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
el 22 de Feb. de 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.
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!