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

3 vues (au cours des 30 derniers jours)
Carina Ufer
Carina Ufer le 16 Fév 2021
Modifié(e) : Jan le 17 Fév 2021
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.

Réponses (1)

Jan
Jan le 16 Fév 2021
Modifié(e) : Jan le 17 Fév 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)
...
end
end
end
  1 commentaire
Carina Ufer
Carina Ufer le 16 Fév 2021
Thanks for the quick answer. I will try to incorporate your suggestions maybe it'll work then.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by