MATLAB: Using conditional statements inside cellfun

cellfunconditional statements

Suppose I have two cell arrays X and Y. If Y{i} satisfies a condition, I want to transform X{i} into some X'{i}, otherwise leave X{i} unchanged. Something like:
for i=1:N
if Y{i}>2, X_out{i} = reshape(X_in{i},...);
else X_out{i} = X_in{i}; end
end
How can I do this with cellfun? Multiplying by false won't work because the transformation involves reshaping X{i}. For example, the following doesn't work:
X_out = cellfun(@(x,y) ~(y>2)*x + (y<=2)*reshape(x,...), X_in, Y);
I presume this question applies to anonymous functions in general.

Best Answer

You cannot use those kinds of conditionals in cellfun, at least not without the use of an auxillary true function that does the equivalent of the C/C++ question-colon operator.
The workaround is
mask = cellfun(@(y) y>2, Y);
X_out = X_in;
X_out(mask) = cellfun(@(xin) reshape(xin, ...), X_in(mask), 'uniform', 0);
Related Question