Appending Values to an Empty Array

조회 수: 277 (최근 30일)
R
R 2022년 5월 7일
답변: dpb 2022년 5월 7일
I am unable to run this simple chunk of code. I am trying to break down over a million points of data in chunks of 6000. I then want to calculate the number of peaks and then return it to an array so that I can calculate the average peaks per 6000 data points.
I am however receiving this error:
Unable to perform assignment because the indices on the left side are not
compatible with the size of the right side.
Error in filter (line 104)
rate(end+1) = peaks;
Why is appending not possible?
rate = [];
for k = 1:size(x):6000
section = sg_filt(k:i,:);
i = k+6000;
[pks] = findpeaks(section, 'Threshold', 500);
peaks = size(pks);
rate(end+1) = peaks;
end

채택된 답변

Walter Roberson
Walter Roberson 2022년 5월 7일
size() always returns a vector. Consider numel()

추가 답변 (1개)

dpb
dpb 2022년 5월 7일
Because as written size() returns a two-vector and rate(end+1) is an address for a single array element -- you're trying to store two values into one location.
I believe w/o testing that since you're passing a column vector that findpeaks will return the pks array as a column vector as well in which case you're looking for
rate(end+1)=size(pks,1);
If it is a column vector instead, then size(pks,2) or just use numel(pks) instead of size()
It would be better to preallocate and store instead of appending -- while this is a small enough of a case that the extra copy operations won't show up, in general try to avoid doing this when can.
Try something more like
N=6000; % use variables, don't bury magic numbers in code
nSeg=ceil(numel(sg_filt)/N); % compute number of segments
rate = zeros(nSeg,1); % preallocate output
for k = 1:N:numel(sg_filt)
section = sg_filt(k:i,1);
i = k+6000;
[pks] = findpeaks(section, 'Threshold', 500);
peaks = size(pks);
rate(end+1) = peaks;
end
I fixed up a few other things based on what I'd guess you want/have as well...

카테고리

Help CenterFile Exchange에서 Descriptive Statistics에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by