× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Apply a function to each sub-cell of a cell in Matlab?

Ray Phan
Jul 02, 2015
<p>Simple. First make a handle to the function where the only input is the cell array:</p> <pre><code>h = @(x) D(x, a, b); </code></pre> <p>Here, <code>x</code> would be a cell from the cell array. Also, I'm going to assume that <code>a</code> and <code>b</code> are already defined in your workspace. After, just do this:</p> <pre><code>out = cellfun(h, C, 'uni', 0); </code></pre> <p>The first argument is a handle to the function, which we've already defined. The next parameter is the cell array you want to operate on and apply the function <code>h</code> to every cell in your array. You need to specify the <code>uni=0</code> flag because the output is <strong>non-uniform</strong>. Because your function outputs a vector per cell, this is mandatory. If your function outputted a single value, then this declaration of <code>uni=0</code> is not required.</p> <p>Alternatively, you can do this in a loop... which is what <code>cellfun</code> ultimately performs:</p> <pre><code>out = cell(numel(C), 1); for idx = 1 : numel(C) out{idx} = D(C{idx}, a, b); end </code></pre> <p>To me, the second option is more suitable for those who aren't used to using <code>cellfun</code>.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/31081492/Apply%20a%20function%20to%20each%20sub-cell%20of%20a%20cell%20in%20Matlab?/31081547">Stack Overflow</a>.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus