Subtract one element from the following inside a loop

9 ビュー (過去 30 日間)
ASM Islam
ASM Islam 2014 年 7 月 8 日
回答済み: Image Analyst 2014 年 7 月 8 日
Say, pres = [99 100 10 20];
Here, pres(3) < pres(2), that is 10 < 100. In such cases I want to return 'pres(4) - pres(3)'.
My code is below which isn't working:
for i=2;
while pres(i) < pres(i-1);
presdiff = pres(i+1) - pres(i);
end
i=i+1;
end
Could anyone point out where the problem is. Thanks.

回答 (3 件)

dpb
dpb 2014 年 7 月 8 日
for i=2
while pres(i) < pres(i-1);
presdiff = pres(i+1) - pres(i);
end
i=i+1;
end
is identically equivalent to
while pres(2) < pres(1);
presdiff = pres(3) - pres(2);
end
i=3;
and since p(2)>p(1), the while clause is never executed
It seems unlikely this is really the actual problem with a fixed set of indices so not sure how to write the general expression for what you're looking for. The actual answer for the specific case alone would be simply
if p(3)<p(2)
dp=p(4)-p(3);
else
dp=p(3)-p(2);
end
I'm guessing you're really looking for a combination of
doc diff
doc find
or in lieu of using find explicitly, using logical indexing to refer to a location of interest.

Ben11
Ben11 2014 年 7 月 8 日
I rearranged a bit your code so it looks like this:
clear all
clc
pres = [99 100 10 20];
presdiff = cell(1,size(pres,2)-1);
for i=2:size(pres,2) % in this case 2:4
if gt(pres(i-1),pres(i)) % if pres(i) is greater than pres(i-1)
fprintf('%i - %i = %i\n',pres(i),pres(i-1),pres(i)-pres(i-1));
presdiff{i} = pres(i) - pres(i-1); % store the difference in a cell array if you need them later on
end
end
Without knowing what you want to do with this that's a start. Here are maybe a few things I changed to your code:
1) When using a for-loop, you need to provide a staring value, an increment and a stopping value for your variable (i). The default is 1, so you see in my code above that I change
for i = 2
into
for i = 2:size(pres,2)
In which size(pres,2) is equivalent to 4 in your case.
2) Don't put a semi-colon after the condition for your while loop, and make sure the condition can be interpreted as true or false. In your code I wrote gt(...) which Matlab interprets as true if the 2nd entry is greater than the 1st one.
3) I don't know what you plan to do with your code so I put a fprintf in order to display the difference between successive entries, and I stored them in a cell array in case you want to use them.
I hope it helped you a bit.

Image Analyst
Image Analyst 2014 年 7 月 8 日
Like dpb said, just use diff
differences = diff(pres);

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by