Domanda

I have a number of cell arrays that have different formats. Some contain only numbers, some contain several numbers in each cell (each cell is a cell by itself), some contain words, and some contain several words in each cell (each cell is a cell by itself). Now I have several problems.

1.Let's say that I have the following matrix :

A' = [1, 2, 3, 4, 5]

I would like to add a header to this column and save it in a new cell s.t.:

A2' = {'Header1', 1, 2, 3, 4, 5}

I am trying:

A2 = {'Header1'; num2str(A)}

But the result is a 2*1 cell array that contains 'Header1' in the first cell and the numbers in the second cell, but I want each number to be in a separate row!

2) For the cells that contain several numbers in each cell, let's say I have the following:

B' = {{1,2,3},{3,4,5},{1,2},1}

I again would like to have a result such that:

B2' = {'Header2',{1,2,3},{3,4,5},{1,2},1}

I did B2 = {'Header2'; num2str(B)};

but I get the error message

Undefined function 'abs' for input arguments of type 'cell'.

3.Lastly, I would like to concatenate the resultant cell arrays and write them in an excel file. I tried: ForExcel = [char(A), char(B), char(C), char(D)]; filename = 'ForExcel.xlsx'; xlswrite(filename, ForExcel);

But I am not getting anything. Note that arrays C and D contain words and they may have several words in each cell.

È stato utile?

Soluzione

I will try to answer your questions:

1) In this case, your concatenation is wrong. Try like that:

A = [1, 2, 3, 4, 5]; A2 = [{'Header1'} num2cell(A)]'

A2 =

'Header1'
[1]
[2]
[3]
[4]
[5]

2) You can't use num2str() function to convert cell arrays, just matrices.

3) Can you give a more detailed explanation of variable ForExcel? Would be great if you could copy and paste the code here.

Regards.

Altri suggerimenti

For #1, do you need the numerical data to be strings? The (only?) nice thing about cell arrays is that data of differing types can coexist.

A = [1, 2, 3, 4, 5]';

A_cell_array_of_doubles = num2cell(A);

A2 = [{'Header1'}; A_cell_array_of_doubles];


A2 = 

    'Header1'
    [1]
    [2]
    [3]
    [4]
    [5]

For #3, note that xlswrite handles these "mixed type" cell arrays just fine.

ForExcel = [A2, A2, A2];
filename = 'ForExcel2.xlsx';
xlswrite(filename, ForExcel);

Ok, the tricky one. For #2, you've got cells within cells - is there any way to simplify this data structure? If not then you probably WILL need to turn all those individual arrays {1,2,3} and {3,4,5} into strings first before using xlswrite.

Looping through your top-level array and using cellfun with num2str on each element may help:

A_cell_array_of_strings = cellfun(@num2str,A_cell_array_of_doubles,'UniformOutput',false)

A_cell_array_of_strings = 

    '1'
    '2'
    '3'
    '4'
    '5'
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top