Cell functions

di il
1 risposte

Cell functions

How can I calculate the square and sum of each elements in a cell , Is there a specific command for extraction of cell elements? Jino

1 Risposte

  • Re: Cell functions

    The cell array is a very useful data type but, unfortunately, not supported by many MatLab built-in functions.

    To extract the elements stored in a cell array a simple "parenthesis notation" could be used: given as an example a (1 x 3) cell array "a_cell_array", its values can be extracted into an array by means of the following instruction:

    an_array=[a_cell_array{:}]

    Notice the "[" and "]" enclosing the cell array and the "{" "}" to refer to all the elements of the cell array.

    In the following script, the proposed solution is implemented for a (3 x 9) cell array.
    
    % 
    % Cell array "c" memory allocation and initialization
    % 
    c=cell(3,9);
    % 
    % Filling of the cell array "c"
    % 
    for i=1:3
       for j=1:9
          c{i,j}=(i+j)+(i-1)*9;
       end
    end
    % 
    % Matrix "m" (same size of cell array "c") memory allocation and
    % initialization
    % 
    m=zeros(size(c));
    % 
    % Extraction of data from the cell array "c" to the matrix "m"
    % Notice the paranthesis types - the trik is there
    % 
    for i=1:3
       m(i,:)=[c{i,:}];
    end
    % 
    % Display cell array "c" and matrix "m" contennts
    % 
    c
    m
    % 
    % Column-wise sum elements of matrix "m" (i. e. cell array "c")
    % 
    sum_b_1=sum(m,1)
    % 
    % Row-wise sum elements of matrix "m" (i. e. cell array "c")
    % 
    sum_b_2=sum(m,2)
    % 
    % Sum of all the elements of matrix "m" (i. e. cell array "c")
    % 
    sum_b=sum(sum(m))
    % 
    % Square root of each element of matrix "m" (i. e. cell array "c")
    % 
    square_b_1=sqrt(m)
    
    Hope this helps.
Devi accedere o registrarti per scrivere nel forum
1 risposte