trimming arrays within cell

11 views (last 30 days)
Andrew
Andrew on 15 Mar 2016
Commented: Adam on 15 Mar 2016
I have a cell array containing many vectors (traces). I would like to use another cell array, containing the index of the first useful number in each vector, to trim the beginning of each vector.
a for-loop method would be:
for t = 1:numel(traces)
traces{t} = traces{t}(first{t}:end)
end
but this is ugly and I feel like there must be a non-for-loop based way of doing this, perhaps using cellfun?
  1 Comment
Adam
Adam on 15 Mar 2016
It depends why you want to replace the for loop. cellfun can usually replace a loop around a cell array if you want it to, but it is usually slower so if speed is your motivation then this is unlikely to help, though obviously it is always worth implementing the two alternatives to test their speed.
For cellfun just create a function of two variables, the vector and the scalar first useful number and run cellfun over your two arrays using this.

Sign in to comment.

Accepted Answer

Jan
Jan on 15 Mar 2016
The shown code is fast and clear. A reader can recognize, what it should do directly. I hestitate to think, that a corresponding cellfun command would be faster or nicer. So you do not get an advantage for debugging or the runtime. Even if the runtime is a little bit faster, the effort for programming and debugging will exceed this time.
So I'd perfer the "solution" not to care about the "ugliness" of such a useful piece of code. I've seen many code, which are much more ugly.
  2 Comments
Guillaume
Guillaume on 15 Mar 2016
Edited: Guillaume on 15 Mar 2016
Well, it all depends on the programmer, beauty is in the eye of the beholder. I'd use cellfun over a loop any day unless speed is critical. To me, cellfun / arrayfun are nicer and easier to debug.
cellfun, arrayfun are nice examples of functional programming. They clearly express the fact that you're transforming one entire sequence into another using a well defined operator. They also have the advantage that you don't have to worry about predeclaring the output and you don't have to worry whether or not the size of the output you've declared is the right size, or if you've got the right bounds for the loop.
For reference, this is the cellfun equivalent of the loop:
traces = cellfun(@(t, f) t(f:end), traces, first, 'UniformOutput', false);
Adam
Adam on 15 Mar 2016
I also tend to favour cellfun where time is not a factor, though it is personal preference. My colleague doesn't consider cellfun to be much "fun" at all and it does require a little more learning and understanding of syntax (though not much when you are used to it)

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!