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

5 visualizaciones (últimos 30 días)
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.

Respuestas (1)

Jan
Jan el 16 de Feb. de 2021
Editada: Jan el 17 de Feb. de 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

Categorías

Más información sobre Logical en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by