using conditional statements inside cellfun

64 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

Walter Roberson
Walter Roberson el 12 de Nov. de 2017
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);

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by