Why does matlab skip my if statement

6 ビュー (過去 30 日間)
Sam Rijkers
Sam Rijkers 2017 年 5 月 2 日
編集済み: Stephen23 2017 年 5 月 2 日
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 件)

Sebastian Castro
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

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by