Search code examples
arraysmatlabconditional-statementscell

How to unnest a nested cell array?


Hello I am trying to create a cell array that should look something like this.

'3/7/2014'  '209.167.128.156'   1037 
'3/13/2014' '204.205.57.137'    8
'3/18/2014' '209.167.128.156'   164
'3/27/2014' '216.178.43.209'    825

But the problem is when I run my code I get a cell array that looks like this

{1x3cell} {1x3 cell} {1x3 cell} {1x3 cell} {1x3 cell]

Here is my code:

cell = {};
month = 'March';
[num text raw] = xlsread(sheet);
text(1,:)= [];
fanta = text(:,1);
[row col] = size(fanta);
a = 1;
for i = 1:row
    coke = fanta{i};
    [first rest] = strtok(coke, '/');
    if strcmp(first, '1') && strcmp(month, 'January')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '2') && strcmp(month, 'February')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '3') && strcmp(month, 'March')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '4') && strcmp(month, 'April')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '5') && strcmp(month, 'May')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '6') && strcmp(month, 'June')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '7') && strcmp(month, 'July')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '8') && strcmp(month, 'August')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '9') && strcmp(month, 'Sepetember')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '10') && strcmp(month, 'October')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '11') && strcmp(month, 'November')
        cell{i} = raw((a+i), :);
    end
    if strcmp(first, '12') && strcmp(month, 'December')
        cell{i} = raw((a+i), :);
    end
end
cell = cell(~cellfun('isempty', cell))

What am I doing wrong and how can I fix it. Thank you.


Solution

  • First, you should never call a variable cell, since it is the name of a built-in Matlab function. This is bad, you should be punished for this :-)

    Let's say you have replaced all cell's by C. Then, you should initially define C by

    C = cell(0,3);
    

    and replace all your

    C{i} = ...
    

    by

    C(i,:) = ...
    

    Last point: the last column will be made of strings an not numbers. You may should consider to use the function str2double somewhere in your code if you really want to have numbers in this column.

    Best,