我一直在尝试使用此代码将x轴值(仅峰值)写入txt文件(此方法正常工作)。
%determine the bpm
%count the dominant peaks in the signal
fid = fopen('y1.txt','a'); %txt naming and append
beat_count = 0;
for k = 2 : length(pbcg)-1
if (pbcg(k) > pbcg(k-1) && pbcg(k) > pbcg(k+1) && pbcg(k) > 1)
beat_count = beat_count + 1;
end
end
fprintf(fid, '%i\n', k); %open writer
fs = 100; %freq 100hz
N = length(pbcg);
duration_in_seconds = N/fs;
duration_in_minutes = duration_in_seconds/60;
BPM_avg = beat_count/duration_in_minutes;
fclose(fid); %close writer
但问题出现在这里,当我修改它以逐段绘制图形时(我设法完成此操作)但问题是当我的代码是时,问题是无法将x轴值写入txt文件像这样......我做错了什么?
%plot segment by segment
data = pbcg;%data value from 1 to 10000
rows = reshape(data, 1000, numel(data)/1000)';%reshape the data into
%matrix by 1000 against total num of element in array and then / 1000)
fid = fopen('y1.txt','a'); %txt naming and append
beat_count = 0;
for e = 1:size(rows,1),
%plot normal & with nodes together
figure,plot(rows(e,:)),hold on,plot(rows(e,:),'ro');
%if statement to find peak
if (pbcg(k) > pbcg(k-1) && pbcg(k) > pbcg(k+1) && pbcg(k)> input('Key in the threshold value: '))
beat_count = beat_count + 1;
peaks(beat_count)=pbcg(k);
end
pause;%pause, on keypress go to next plot
fprintf(fid, 'x_axis%i\n ', peaks); %open writer
end
fclose(fid); %close writer
即使我输入了阈值,我得到的结果仍然是整个峰值列表。
答案 0 :(得分:0)
您需要将input
语句放在循环之外,否则将多次计算(每次所有其他条件都为真)。但实际上,有更有效的方法可以做你想要的 - 基于matlab喜欢语句被矢量化(一次操作整个数组)的事实。以下是一些想法:
rows = reshape( data, 1000, []); % the [] means "figure out what this dimension has to be so it works"
d1 = diff( rows, 1 ); % take "first derivative" along first non-singleton dimension
pkLocs = find(d1(1:end-1,:)>0 & d1(2:end,:) < 0 ); % peak = where derivative changes sign
threshold = input('Key in the threshold value:');
[pk_i pk_j] = ind2sub( size(d1), pkLocs );
pkVals = rows( sub2ind( size(rows), pk_i, pk_j) );
aboveThr = find( pkVals > threshold );
goodPk_i = pk_i( above_thr );
goodPk_j = pk_j( above_thr );
for j = 1:size(rows, 2)
fprintf( 1, 'peaks found for segment %d:\n' );
fprintf( 1, '%f ', goodPk_i(goodPk_j == j ) );
end
看看这是否有助于你搞清楚!
您所说问题的一个更简单的答案:您需要在k
上创建一个内部循环,并对您的代码进行一些其他更改,如下所示:
beat_count = 0;
for e = 1:size(rows,1),
%plot normal & with nodes together
figure,plot(rows(e,:)),hold on,plot(rows(e,:),'ro');
threshold = input('Key in the threshold value to use: ');
% loop over this if statement to find peaks in this row
for k = 2 : 999
if (rows(e,k) > rows(e, k-1) && rows(e,k) > rows(e,k+1) && rows(e,k) > threshold)
beat_count = beat_count + 1;
peaks(beat_count)=rows(e,k);
peak_x(beat_count) = k + 1000 * (e - 1);
end
end
fprintf(1, 'press any key to continue!\n');
pause; % pause, on keypress go to next plot
end
% since peaks array keeps growing, we should print it out all at once:
fprintf(fid, 'the following peaks were found:\n');
for ii = 1:beat_count
fprintf(fid, 'x = %d; peak = %f\n ', peak_x(ii), peaks(ii)); %open writer
end
fclose(fid); % close the file once you're done
写入免责声明,无法访问您的数据,且无法访问Matlab - 可能存在语法错误,但应该非常接近