0

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.

tytamu
  • 555
  • 3
  • 11
  • 20

2 Answers2

3

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
Eitan T
  • 32,660
  • 14
  • 72
  • 109
  • @ EitanT, thanks for the fast reply, what will you suggest if the length (number of rows) of the matrix inside of each cell are different ?? – tytamu Mar 09 '13 at 22:37
  • @Tai-YenChen As I've already mentioned in the answer, use a `for` loop. It's not as a slow as you'd expect... :) – Eitan T Mar 09 '13 at 22:39
  • 1
    @ EithanT, I did not see the information about the for loop in the answer before my post, XD. Thanks again. – tytamu Mar 09 '13 at 22:43
1

You can add a matrix to each cell as shown below:

B=cellfun(@(x) x+[0 0 0 100 0;0 0 0 100 0],A,'UniformOutput',false); 
Autonomous
  • 8,935
  • 1
  • 38
  • 77