How to transform a double loop into a single 'Cellfun' statement
Mostrar comentarios más antiguos
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 comentarios
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
el 31 de Oct. de 2012
Editada: Sean de Wolski
el 31 de Oct. de 2012
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
Respuestas (2)
Andrei Bobrov
el 31 de Oct. de 2012
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
el 1 de Nov. de 2012
0 votos
Categorías
Más información sobre Whos en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!