How to add an unknown amount of number in matlab?

11 次查看(过去 30 天)
I am creating a code to get the resultant of an unknown number of vectors by addition. I can't think of a way to add unknown amount of numbers in a loop. Here's my code so far. It only adds two numbers in that kind of equation.
for n=2:1:sv(2)
xx=vect{1,n-1}(1)+vect{1,n}(1)
end

回答(2 个)

David Sanchez
David Sanchez 2014-10-20
Not sure about your intentions, i created a dummy cell and a solution for what i think is your problem:
vect=cell(5,3);% initialization of dummy cell
for r=1:5
for c=1:3
vect{r,c} = rand(3,1); % random 3x1 array in each cell
end
end
%%%the sumation
xx = 0; % initialize summation
for n=1:length(vect(1,:)) % for-loop from first to last (unknown) element
xx = xx + vect{1,n}(1); % iterate along the column
end

David Young
David Young 2014-10-20
The trick is to add on to the result vector each time through the loop.
I don't understand what sv is in your code, and I'm not sure why you select the first element of each vector, so here's a simpler example which adds up all the vectors stored as elements of a cell array, assuming they are all the same size:
% example data
vect = {[1 2 3] [4 5 6] [7 8 9]}; % can have any number of elements
sumVec = 0;
for ii = 1:numel(vect)
sumVec = sumVec + vect{ii};
end
If your initial vectors are stored as the rows or columns of a matrix, it's even simpler - just a single call to the sum() function.

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by