using conditional statements inside cellfun

47 次查看(过去 30 天)
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.

采纳的回答

Walter Roberson
Walter Roberson 2017-11-12
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);

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by