Effacer les filtres
Effacer les filtres

using conditional statements inside cellfun

60 vues (au cours des 30 derniers jours)
Kaushik Lakshminarasimhan
Kaushik Lakshminarasimhan le 12 Nov 2017
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.

Réponse acceptée

Walter Roberson
Walter Roberson le 12 Nov 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);
  1 commentaire
Kaushik Lakshminarasimhan
Kaushik Lakshminarasimhan le 12 Nov 2017
This is not a bad workaround. Thanks!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by