I have a cell with different types of variables (double & strings), I want to round the numeric elements in the cell.
round
function can work only with arrays and not with cells, so I'm trying to use cell2mat
- but this function can't be used in case of different elements types in the cell.
Any idea how can I round the numeric elements in this cell? Of course I don't want to do loop over the cell elements.
As mentioned by Adriaan, this can be done with cellfun
:
function testCell = q38476362
testCell = {'t','h',1.004,'s',[],'i',4.99,[],'a',[],'ce',10.8};
isnum = cellfun(@(x)~isempty(x) & isnumeric(x),testCell);
testCell(isnum) = num2cell(round([testCell{isnum}],0));
testCell =
't' 'h' [1] 's' [] 'i' [5] [] 'a' [] 'ce' [11]
If your cell array is random in terms of where the string
s and where the double
s are, there's not much you can do besides loop/cellfun
/bruteforce. If however, there is some periodicity (e.g. "a string is always followed by two double
entries") you might be able to construct some indexing vector that would get you the values without having to iterate (explicitly or implicitly).