2

I'm trying to do the following:
Let's say I have:

x1=[7];
x2=[3 4];
x3=[1 -1 5];
x4=[2 5 -1 3];

and I want to add them together.
I know it's not possible to add vectors of different dimensions, but what I'm trying to achieve is a new vector having:

v=[2 5+1 -1-1+3 3+5+4+7];

I tried to pad the relevant vectors with zeros, to get:

x1=[0 0 0 7];
x2=[0 0 3 4];
x3=[0 1 -1 5];
x4=[2 5 -1 3];

and then the addition will be natural, but couldn't find a way to do it.
Of course, I'm looking for an iterative method of doing that, meaning, every vector xi is the result of the i'th iteration, where the number of iterations, n, is known in advance. (in the above example n=4)

so.very.tired
  • 2,958
  • 4
  • 41
  • 69
  • Maybe I'm looking at this wrong, but there doesn't seem to be an easy to recognize pattern to your vector addition. – James Mertz Jun 09 '14 at 21:22
  • You're right, sorry... let me edit my post... – so.very.tired Jun 09 '14 at 21:31
  • 1
    Does each vector have one more element that the previous one? And why don't you store vectors as cells of a cell array? That is, `x{1}`, `x{2}` etc. It would be easier and avoid `eval` – Luis Mendo Jun 09 '14 at 21:33
  • every vector is completely different from the one that was calculated in previous iteration. – so.very.tired Jun 09 '14 at 21:34
  • 1
    Use this solution to get a regular matrix with the data: http://stackoverflow.com/questions/3054437/how-can-i-accumulate-cells-of-different-lengths-into-a-matrix-in-matlab . You want zeros on the left instead nans on the right, so you have to use `fcn = @(x) [zeros(1,maxSize-numel(x)) x];`. Finally, use `sum` to get the sum. – Daniel Jun 09 '14 at 21:36

1 Answers1

3

My first thought would be something like

x1 = [zeros(1, 4 - length(x1)) x1];

Where you would substitute max(all_your_arrays) for 4 in the above line. If your arrays are in cell arrays you should be able to easily adapt that to a loop.

laaph
  • 301
  • 1
  • 4