Appending Values to an Empty Array

272 vues (au cours des 30 derniers jours)
R
R le 7 Mai 2022
Réponse apportée : dpb le 7 Mai 2022
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

Réponse acceptée

Walter Roberson
Walter Roberson le 7 Mai 2022
size() always returns a vector. Consider numel()

Plus de réponses (1)

dpb
dpb le 7 Mai 2022
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...

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by