How to transform a double loop into a single 'Cellfun' statement
이전 댓글 표시
Hi, I am still quite new to Matlab and trying to get my head around the concept of Vectorization. I have a specific question regarding how to transfer what I am currently solving using a double loop to a 'Cellfun' statement.
The code I would like to 'simplify' is as follows:
==============
vFilter = cell(size(mUnsortedNodes,1),size(mUnsortedNodes,2));
for irow=1:size(mUnsortedNodes,1)
for icolumn=1:size(mUnsortedNodes,2)
vFilter{irow,icolumn} = strrep(strcat(mUnsortedNode{irow,1:icolumn}),' ','');
end
end
=============
In simple terms this is what I am trying to do: mUnsortedNodes is a 32x4 Cell Array. For each row I would like to concatenate the columns across, so Cell 1,1 is itself, Cell 1,2 concatenates the first two cells in the first row, Cell 1,3 concatenates the first three cells of the first row etc.
My problem is that I cant get the increasing concatenation of the columns to work (the 1:icolumn bit).
Any ideas how to get this to work with CellFun?
Any hint would be much appreciated - Thanks
Sven
댓글 수: 2
I'm not entirely clear on your question. The code as you've written it looks like it should work. Are you saying that it does not? If so what's the problem.
Are you just asking how you would do it with CELLFUN? The operation is complicated enough that a direct for-loop is the easiest and most readable to code, I think. This isn't the kind of situation where people use CELLFUN.
Sean de Wolski
2012년 10월 31일
편집: Sean de Wolski
2012년 10월 31일
cellfun is also a bad example of vectorization. Usually, when I've timed it, cellfun is slower than a for-loop. The reason I use it occasionally is it's easy, if say you want to do something where speed doesn't matter but ease of writing the code does. E.g:
C = cellfun(@sin,C,'uni',false)
This is much easier than:
for ii = 1:numel(C)
C{ii} = sin(C{ii});
end
답변 (2개)
Andrei Bobrov
2012년 10월 31일
s = mUnsortedNodes;
[x,y] = ndgrid(1:size(s,1),1:size(s,2));
vFilter = arrayfun(@(i1,i2)strrep(strcat(s{i1,1:i2}),' ',''),x,y,'un',0);
카테고리
도움말 센터 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!