for loop in an array to substract the values of the array and find a specific value
Afficher commentaires plus anciens
I have an array of 200 values. This is the operation I need to program:
The value in the position X minus the value in the position Y EQUALS 0.55. Therefore, I am using a for loop and If statement.
The problem is that I know neither value nor the position of each value. I guess both of them are in the first 50 values of the array. So, how can I code the operation below n times (k-1, k-2, k-3 ...) until I got this number, and disp the 'Here'?
I;
for k =length (I)
x=I(k)-I %Take last value and substract the first value of I, second, k times to the last value.
if x==0.55
disp 'Here'
else
disp 'Not here'
end
end
Réponse acceptée
Plus de réponses (2)
Subhadeep Koley
le 1 Fév 2020
Try this.
for k = 2:length(I)
x = I(k) - I(k-1);
if x == 0.55
disp('Here');
else
disp 'Not here'
end
end
Image Analyst
le 1 Fév 2020
Modifié(e) : Image Analyst
le 1 Fév 2020
First of all read the FAQ : Click here to learn why you shouldn't use == to compare floating point values. You should use ismembertol():
x = zeros(size(I));
for k = 1 : length(I)
% Take last value and substract the first value of I, second, k times to the last value.
% I have no idea what the above means but let's subtract I(1) and see
x(k) = I(k) - I(1);
if ismembertol(x(k), 0.55, 0.004)
fprintf(' ----> Found a match at index %d where I(%d) = %f and x = %f.\n', k, k, I(k), x);
break; % Let's quit when we find a match.
else
fprintf('Found no match at index %d where I(%d) = %f and x = %f.\n', k, k, I(k), x(k));
end
end
histogram(x);
5 commentaires
Jose Rego Terol
le 1 Fév 2020
Jose Rego Terol
le 1 Fév 2020
Image Analyst
le 1 Fév 2020
Why use a loop? To subtract all values from I(1) and get a new vector with those differences, do
IDiff = I(1) - I;
Then to see which are closer than 0.004 (or whatever tolerance you want) to 0.55, do
indexes = find(abs(IDiff - 0.55) > 0.004);
I don't see how any loop is needed.
Jose Rego Terol
le 1 Fév 2020
Jose Rego Terol
le 1 Fév 2020
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!