Search code examples
matlabcell-array

add a constant to a specified column of a matrix for a cell array in matlab


Assume I have a 4x1 cell array,A, inside each cell is a 2x5 matrix,

A={[1 1 1 1 1; 2 2 2 2 2];
   [3 3 3 3 3; 4 4 4 4 4];
   [5 5 5 5 5; 6 6 6 6 6];
   [7 7 7 7 7; 8 8 8 8 8]}

what I want is to add a constant,let's say 100, to the 4th column of matrix for each cell to make B. For example

B={[ 1 1 1 101 1; 2 2 2 102 2];
   [3 3 3 103 3; 4 4 4 104 4];
   [5 5 5 105 5; 6 6 6 106 6];
   [7 7 7 107 7; 8 8 8 108 8]}

What is the best way to do it?

I can get the addition result by using

B=cellfun(@(x) x(:,4)+100,A,'uni',0) 

but have difficult to get B. Any help is greatly appreciated.


Solution

  • If you can guarantee that the matrix in cell in A is of the same dimensions (in your case, a 2x5 matrix), you can concatenate all matrices vertically:

    B = cat(1, A{:});
    

    then add 100 to the fourth column:

    B(:, 4) = B(:, 4) + 100;
    

    and then convert back it back to a cell array:

    B = mat2cell(B, size(A{1}, 1) * ones(size(A)), size(A{1}, 2));
    

    In this case consider representing the data as a three-dimensional matrix instead of a cell array. It would be much easier to manipulate.

    In the general case, you would employ a for loop:

    B = A;
    for k = 1:numel(A)
        B{k}(:, 4) = B{k}(:, 4) + 100;
    end