subtracting a particular value until that the result becomes negative
조회 수: 1 (최근 30일)
이전 댓글 표시
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
Adam
2017년 2월 22일
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.
채택된 답변
Jan
2017년 2월 22일
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개)
dpb
2017년 2월 22일
편집: dpb
2017년 2월 22일
>> 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
Bas Holten
2017년 2월 22일
'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
2017년 2월 22일
As Bas says, it's that initial point; was 6 in your example. I missed it in the cut'n paste. Fixed in answer.
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!