subtracting a particular value until that the result becomes negative
5 ビュー (過去 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 件のコメント
その他の回答 (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!