Why do I get a different result of calculation in for loop than in command line

조회 수: 3 (최근 30일)
Carina Ufer
Carina Ufer 2021년 2월 16일
편집: Jan 2021년 2월 17일
Hi,
I have a 240x1 cell array which contains a different amount of values each (around 1x~20). I need to compare each consecutive value difference to check if it exceeds a threshold. So I loop over the cell array and calculate the size of the current cell-1 to loop over those values:
for b = 1:length(A) % for 240
count = length(A{b})-1; % for as many values as in array-1
for e = 1:count
if ((A{b}(e+1) - A{b}(e)) <= x )
...
end
end
end
However the calculation of
count = length(A{b})-1;
gives me the wrong value each time in the loop being length+1 (e.g. length would be 19 but the value of the count variable is 20) in the first iteration while once I copy the exact same line and execute it in the command window it shows the correct result of length(A{b})-1.
What is my logical error here? How can I solve this? I tried different variataions of brackets but nothing worked. This just seems unlogical to me.

답변 (1개)

Jan
Jan 2021년 2월 16일
편집: Jan 2021년 2월 17일
Your analysis is correct: it seems unlogical. For an experiences programmer this is a secure signal, that something happens, which is out of sight. The only valid explanation is, that you use different input data or that you have modified the file but did not save it before running the code.
The code looks correct, so the problem is somewhere else.
Some ideas for cleaning the code:
for b = 1:numel(A) % LENGTH is correct, but tricky.
% If NUMEL is meant, use NUMEL. Or SIZE(A, 1)
match = diff(A{b}) > x; % Slightly faster, maybe nicer
count = numel(A{b}) - 1; % for as many values as in array-1
for e = 1:count
if match(count)
...
end
end
end
  댓글 수: 1
Carina Ufer
Carina Ufer 2021년 2월 16일
Thanks for the quick answer. I will try to incorporate your suggestions maybe it'll work then.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by