Search code examples
matlabcell-array

How to build a cell-array or matrix of different dimension


I'm using the findpeaks method in Matlab to find peaks. I have a matrix(Peak) of 260x601 where its 260 different trials over 601 time points. I have a separate vector for the actual time (called TimeVec).

I'm using a for loop to loop over the trials.

for i = 1:size(Peak,1)
    [pks(i),locs(i)]=findpeaks(Peak(i,:),timeVec,'MinPeakHeight',1);
end

The problem is that each trial could have a different number of peaks therefore it's trying to combine a different number of columns to each iteration. How can I get around this?


Solution

  • This is a short and not fully efficient method:

    fp = @(k) findpeaks(Peak(k,:),timeVec,'MinPeakHeight',1);
    [pks,locs] = arrayfun(fp,1:size(Peak,1),'UniformOutput',false);
    

    it will be a bit faster with a for loop, but it worth changing this only if you have more data:

    [pks,locs] = deal(cell(size(Peak,1),1));
    for k = 1:size(Peak,1)
        [pks{k},locs{k}] = findpeaks(Peak(k,:),timeVec,'MinPeakHeight',1);
    end
    

    for further manipulations on that, use @excaza advice and read the cell array docs.