# How to extract peaks from a matrix and concatenate columns with different number of rows using a loop?

3 views (last 30 days)
Emerson De Souza on 20 Apr 2011
Hi I want to extract the peaks of all columns from a matrix M.
Each column of M should generate a new column of a matrix N
with the PEAKS as elements.
I tried the following loop:
for n=1:10
NPEAKS{n} = (findpeaks(M(:,n:n)))';
ALLPEAKS=[NPEAKS{1:n}];
end;
The second line of the loop works fine
and I obtain in each { } the desired column with the peaks.
However, the concatenation (third line of the loop)
of all columns to ONE new matrix did not work
because the amount of peaks (or elements) found for each
columns differs from column to columns.
How can I correct the commands above or to obtain the same result
doing something else.
Emerson

Andrei Bobrov on 20 Apr 2011
variant of using cellfun
M = randi(1500,12,12);
[p,l] = arrayfun(@(x)findpeaks(M(:,x)),1:size(M,2),'UniformOutput',false);
iend = cellfun('size',l,2);
iendmax = max(iend);
NPEAKSdouble = cell2mat(arrayfun(@(x,y,z)[cat(3,x{:}.',y{:}.');zeros(iendmax-z,1,2)],p,l,iend,'UniformOutput',false));
variant of using for loops
M = randi(1500,12,12);
nM = size(M);
N = 0;
NPEAKSdouble = zeros([nM,2]);
for jj = 1:nM(2)
[p,l] = findpeaks(M(:,jj));
lp = length(p);
N = max(N,lp);
NPEAKSdouble(1:lp,jj,:) = cat(3,p,l);
end
NPEAKSdouble = NPEAKSdouble(1:N,:,:);
##### 2 CommentsShowHide 1 older comment
Andrei Bobrov on 20 Apr 2011
Dear Oleg agree with you, I'll be corrected, hurry. Thank you