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

Matt J
Matt J 2012년 10월 31일
편집: Matt J 2012년 10월 31일
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.
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
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);
Sven
Sven 2012년 11월 1일

0 개 추천

Hi Andrei, thanks for the code, that is exactly what I was looking for! I wasn't aware of the ndgrid fucntion.
Others, I am still new to Matlab and trying to figure out how things can be done with the different fucntions. Sven

카테고리

질문:

2012년 10월 31일

Community Treasure Hunt

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

Start Hunting!

Translated by