I googled but couldn't find anything although I think this a general need.
I use this function in Matlab to insert an object in to a cell:
function ce = insertInCell(ce,toInsert,idexx)
ce = [ce(1:idexx-1,1); cellToInsert; ce(idexx:end,1);];
end
I think this function works like this:
1st: creates a new cell by copying ce(1:idexx-1,1)
2nd: adds cellToInsert to this new cell
3nd: copies and adds ce(idexx:end,1); to the new cell
and I was wondering if there is a more efficient way of doing this? I mean a function that just updates the indices of the elements (Or I'm wrong and this function is efficient?)
Thanks.
MATLAB does not expose pointers, therefore you can't just update the indices (pointers), unless you write a MEX file for that purpose.
There is a bug in your code: in code you refer to a variable cellToInsert
, but in the function definition you have only toInsert
.
Your code only works for vertical cell arrays. It does not work for horizontal cell arrays or n-dimensional cell arrays. For vertical cell arrays it works with the toInsert
-> cellToInsert
fix.
Bugfixed version:
function ce = insertInCell(ce,cellToInsert,idexx)
ce = [ce(1:idexx-1); cellToInsert; ce(idexx:end) ];
end