How to add an unknown amount of number in matlab?

8 Ansichten (letzte 30 Tage)
Gennie am 20 Okt. 2014
Bearbeitet: Image Analyst am 22 Okt. 2014
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)

Antworten (2)

David Sanchez
David Sanchez am 20 Okt. 2014
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
%%%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

David Young
David Young am 20 Okt. 2014
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};
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.



Community Treasure Hunt

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

Start Hunting!

Translated by