0

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.

Dev-iL
  • 23,742
  • 7
  • 57
  • 99
erez
  • 399
  • 1
  • 6
  • 17
  • You can't do that without looping afaik. You can use `cellfun` , but that's just a loop in disguise. Cells are notoriously hard to work with if you want to avoid looping. – Adriaan Jul 20 '16 at 08:50

2 Answers2

1

You want to take advantage of the str2double ability to convert non-numeric types into NaN.

Say you have a cell like:

 A = {'1.999','3.1415','pie','??'}
 B = round(str2double(A))

 B =

 2     3   NaN   NaN
GameOfThrows
  • 4,510
  • 2
  • 27
  • 44
1

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 strings and where the doubles 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).

Community
  • 1
  • 1
Dev-iL
  • 23,742
  • 7
  • 57
  • 99
  • Dev-iL, thanks, your answer is great but not working for me in case that cell contain also empty elements ([]) – erez Jul 20 '16 at 09:43