Cellfun not working for cells contain cells?

조회 수: 8 (최근 30일)
Xiaohan Du
Xiaohan Du 2017년 12월 20일
댓글: Jan 2017년 12월 20일
Hi all,
I have a cell like this
K>> respCol
respCol =
1×24 cell array
Columns 1 through 5
{3×1 cell} {3×1 cell} {3×1 cell} {3×1 cell} {3×1 cell}
Columns 6 through 10
{3×1 cell} {3×1 cell} {3×1 cell} {3×1 cell} {3×1 cell}
Columns 11 through 15
{3×1 cell} {3×1 cell} {3×1 cell} {3×1 cell} {3×1 cell}
Columns 16 through 20
{3×1 cell} {3×1 cell} {3×1 cell} {3×1 cell} {3×1 cell}
Columns 21 through 24
{3×1 cell} {3×1 cell} {3×1 cell} {3×1 cell}
and each cell contains
K>> respCol{1}
ans =
3×1 cell array
[1034×2 double]
[ 2×2 double]
[ 6×2 double]
Now I'd like to make the arrays in each cell negative using cellfun, I tried this but didn't work
K>> cellfun(@(v) -v, respCol, 'un', 0)
Undefined unary operator '-' for input arguments of type 'cell'.
Error in beam>@(v)-v
So how can I do it?
Many thanks!
  댓글 수: 1
per isakson
per isakson 2017년 12월 20일
You increase the chance to receive an answer if you upload some data to use for testing of the answer.

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 2017년 12월 20일
Your cellfun code simply says: negate the content of each cell in the outer cell array. However, that content is itself a cell array and matlab doesn't know how to negate a cell array. So you need another cellfun to go into these inner cell array:
cellfun(@(x) cellfun(@uminus, x, 'UniformOutput', false), respCol, 'UniformOutput', false)
Note that
cellfun(@uminus, cellarray) %uminus is the function name of the negate operator -
will be faster than
cellfun(@(x) -x, cellarray)
  댓글 수: 2
Xiaohan Du
Xiaohan Du 2017년 12월 20일
This totally works, thanks!
Jan
Jan 2017년 12월 20일
+1. cellfun(@uminus, cellarray) is nice. But it might be worth to compare the run time with a dull loop:
for i1 = 1:numel(respCol)
C = respCol{i1};
for i2 = 1:numel(C)
C{i2} = -C{i2};
end
respCol{i1} = C;
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by