Why does matlab skip my if statement
5 次查看(过去 30 天)
显示 更早的评论

In my MATLAB script, if statement does not function properly. I have found a way to avoid the part that is malfunctioning, but I wonder what went wrong. All if statements work, except for 'kg == 3.9'. The software does not recognize this and it skips this statement, and continues to process the data with the 'else' statement. In the image provided, you can see the problem while I was debugging. The script that is used is attached below.
clear;
kg = 0;
i = 1;
j = 1;
while kg < 6.6;
filename = ['experiment2_', num2str(kg), 'kg.sig'];
[data,extrainfo]=loadmat(filename);
% First column is EMG data of Deltoid, second and third are from
% contralateral trunk muscles.
if kg == 2.6 || kg == 3.9
data(:,1) = data(:,1)*2;
elseif kg == 5.2 || kg == 6.5
data(:,1) = data(:,1)*4;
data(:,2:3) = data(:,2:3)*2;
else
data = data;
end
% Time axis
N=length(data);fs = 2000;dt = 1/fs;k=[0:N-1];t=k*dt;
% ARV
data_ARV = mean(abs(data));
ARV(i,1:3)=data_ARV;
% RMS
data_RMS = sqrt(mean(data.^2));
RMS(i,1:3)=data_RMS;
% Determine mean power frequency (MPF) and median frequency (MF)
% data is the raw EMG, sfreq is the sample frequency
[p,f]=pwelch(data,fs,round(0.9*fs),fs,fs);
MPF(i,1:3)=sum(p.*f)./sum(p);
x=sum(p);
x1=cumsum(p);
[m,ind]=min(abs(0.5*x-x1));
MF(i,1:3)=f(ind);
kg = kg+1.3;
i = i+1;
end
1 个评论
回答(1 个)
Sebastian Castro
2017-5-2
This is a common issue when working with floating-point numbers, and I would first refer you to this answer: https://www.mathworks.com/matlabcentral/answers/57444-faq-why-is-0-3-0-2-0-1-not-equal-to-zero
You can easily check your specific case in MATLAB, since you're starting with a value of 2.6 and adding 1.3 to it. What does the following expression return?
(2.6 + 1.3) == 3.9
Typically, floating-point equality should be done within some tolerance -- for example
abs(kg - 3.9) < tol
where tol is a (usually) small number that makes sense for your application.
Sebastian
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!