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

3 views (last 30 days)
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 )
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.

Answers (1)

Jan on 16 Feb 2021
Edited: Jan on 17 Feb 2021
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)
  1 Comment
Carina Ufer
Carina Ufer on 16 Feb 2021
Thanks for the quick answer. I will try to incorporate your suggestions maybe it'll work then.

Sign in to comment.


Find more on Loops and Conditional Statements in Help Center and File Exchange




Community Treasure Hunt

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

Start Hunting!